除了 for() loop 之外, 另一個選擇.forEach():
let data = [1, 2, 3, 4, 5];
let sum = 0;
data.forEach(function(value){
sum += value;
});
sum; // 15
這個 forEach() 似乎變成主要的用法, 在 bootstrap 的範例裡, 非常地常見到:
https://getbootstrap.com/docs/5.3/components/scrollspy/
Non-visible elements
Target elements that aren’t visible will be ignored and their corresponding nav items won’t receive an .active
class. Scrollspy instances initialized in a non-visible wrapper will ignore all target elements. Use the refresh
method to check for observable elements once the wrapper becomes visible.
document.querySelectorAll('#nav-tab>[data-bs-toggle="tab"]').forEach(el => {
el.addEventListener('shown.bs.tab', () => {
const target = el.getAttribute('data-bs-target')
const scrollElem = document.querySelector(`${target} [data-bs-spy="scroll"]`)
bootstrap.ScrollSpy.getOrCreateInstance(scrollElem).refresh()
})
})