我正在遍历一个数组,监听点击声。 一旦检测到点击,所有类都会被删除,然后使用它添加类。
我已经移动了 this 关键字,这就是我能想到的。
//vars for the buttons of the top carousel
const tCBtn = document.querySelectorAll('.featureNav li');
//add listener for options choice
for(i = 0; i < tCBtn.length; i++){
tCBtn[i].addEventListener('click', () => {
for(o = 0; o < tCBtn.length; o++) {
tCBtn[o].classList.remove('carousel--active');
this.classList.add('carousel--active');
}
})
}
所有数组项都毫无问题地删除了类,然后我希望将类添加到使用“this”单击的数组项中,但它一直说:
TypeError: Cannot read property 'add' of undefined
at HTMLLIElement.
最佳答案
我相信您的问题是由于使用箭头函数而出现的。这些没有自己的 this
。
您可以尝试用普通函数替换箭头函数,因为普通函数确实有自己的 this
。如果在循环完成后添加 carousel--active
类,效果也会更好。
for(let i = 0; i < tCBtn.length; i++){
tCBtn[i].addEventListener('click',
function() {
for(let o = 0; o < tCBtn.length; o++) {
tCBtn[o].classList.remove('carousel--active');
}
this.classList.add('carousel--active');
}
);
}
参见MDN .
关于javascript - this 关键字和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639783/