javascript - this 关键字和数组

标签 javascript arrays this

我正在遍历一个数组,监听点击声。 一旦检测到点击,所有类都会被删除,然后使用它添加类。

我已经移动了 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/

相关文章:

Firefox 4 和 5 : invalid 'in' operand this. _sandBox - 资源 ://gre/components/nsProxyAutoConfig. js

javascript - 在javascript中连接分割字符串

javascript - 使用 Angular ng-swipe-left 和 ng-swipe-right 在滑动过程中旋转图像

java - 如何将多组ArrayList合并为一组ArrayList

c - 初始化指向字符串数组的指针

javascript - 如何在 HTML Canvas 中以给定 Angular 找到距离给定坐标最近的坐标

java - 二维数组对角填充

class - Go,在 struct 中如何引用当前对象(就像 java 和 c++ 中的这样)?

javascript - 轻松设置 "this"变量?

java - 类的构造函数中有问题