【问题标题】:Why the foreach classlist.remove iteration is not working?为什么 foreach classlist.remove 迭代不起作用?
【发布时间】:2021-08-03 17:12:06
【问题描述】:

我的滑块中的这段代码有问题。 我需要从所有数组元素中删除一个类。数组的长度可能会有所不同。 此代码有效:

updateGallery() {
    this.carouselArray.forEach((el, i ) => {
        el.classList.remove('gallery-item-1');
        el.classList.remove('gallery-item-2');
        el.classList.remove('gallery-item-3');
        el.classList.remove('gallery-item-4');
        el.classList.remove('gallery-item-5');
    });
    let carouselSliceLength = this.carouselArray.slice().length;
    this.carouselArray.slice(0, carouselSliceLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

但是这段代码不起作用:

updateGallery() {
    this.carouselArray.forEach((el, i ) => {
       el.classList.remove(`gallery-item-${i+1}`);
    });
    let carouselSliceLength = this.carouselArray.slice().length;
    this.carouselArray.slice(0, carouselSliceLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

为什么?

【问题讨论】:

  • 这个"gallery-item-" + $i怎么样?
  • i 是数组中元素的位置。这绝对不是数字 1-5。即便如此,你也只有一个电话给.remove(),而不是五个。
  • 你为什么不尝试打印i(使用console.log)看看它显示了什么?
  • 你为什么打电话给slice这么多?
  • 请编辑您的问题以包含 HTML、JavaScript 等,以便在您的问题中重现您的问题。

标签: javascript loops foreach iteration


【解决方案1】:

好的,开发人员。 我在一个循环中循环并更正了代码。 此代码有效。删除类并添加新类。 3d 滑块有效。

updateGallery() {
    const carouselLength = this.carouselArray.length
    this.carouselArray.forEach(el => {
        for (let i=1; i<=carouselLength; i++) {
            el.classList.remove(`gallery-item-${i}`);
        }
    });
    this.carouselArray.slice(0, carouselLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

谢谢!

【讨论】:

    【解决方案2】:

    因为你在做不同的事情。在第一个实现中,您要为数组中的一个元素移除五个不同的元素(对 remove 函数的五次调用)。

    而第二种实现只为每个元素调用一个remove。因此,对于第一个元素,它将删除 gallery-item-1 为第二个 gallery-item-2 等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 2020-01-27
      相关资源
      最近更新 更多