【问题标题】:forEach loop, stacks classesforEach 循环,堆栈类
【发布时间】:2015-08-10 07:46:32
【问题描述】:

我有一个使用 forEach 循环复制的 hmtl 模板。我使用模板的 .length 来赋予新的 div 类名,这些类名是唯一的。

问题是它最新的模板包含所有以前的类。

"residentRetainRequest check jqbr_active residentRetainRequest-0 residentRetainRequest-1 residentRetainRequest-2 residentRetainRequest-3"

如何摆脱以前的课程而只保留最新的课程?所以上面的结果是“residentRetainRequest check jqbr_active residentRetainRequest-3”。

Parts of the code

背后的原因:

temp.find('.residentRetainRequest').attr 'data-key', 'residentRetainRequest-' + iCnt

是不是我用了另一个函数,用这个来调用它。

【问题讨论】:

  • 您确定要为其添加class 的元素对吗?添加类后,通过更改temp.find('.someclass').addClass('newClass').removeClass('someClass');等事件删除classname
  • 或仅将具有当前计数的类添加到最新元素:temp.find('.residentRetainRequest').last().addClass("residentRetainRequest-" + iCnt)
  • 抱歉不够清楚。但我希望所有元素都以 residentRetainRequest- + iCnt 作为类名。但只有一个。不是"residentRetainRequest check jqbr_active residentRetainRequest-0 residentRetainRequest-1 residentRetainRequest-2 residentRetainRequest-3"
  • 所以只需选择最后一个元素(而不是始终使用 .residentRetainRequest 的所有元素)并添加类 residentRetainRequest-i。
  • 谢谢,解决了! :)

标签: javascript jquery html loops foreach


【解决方案1】:

问题似乎是这行代码总是选择所有具有类 residentRetainRequest 的项目:

temp.find('.residentRetainRequest').addClass("residentRetainRequest-" + iCnt);

相反,此代码将仅选择最后一项以添加当前计数为 i 的 residentRetainRequest:

temp.find('.residentRetainRequest').last().addClass("residentRetainRequest-" + iCnt)

【讨论】:

    【解决方案2】:

    解决方案是使用 .removeClass 作为提及。

    temp.find('.residentRetainRequest').addClass("residentRetainRequest-" + iCnt)
    temp.find('.residentRetainRequest').removeClass('residentRetainRequest-' + (iCnt - 1))
    

    因此,我将摆脱以前的课程,只保留最后一门课程。

    【讨论】:

    • 在我看来,两行代码没有必要这样做,因为它们会再次添加和删除。另外,例如,如果您有索引 1、2、3、4。您添加 5 并删除 4,但仍保留 1、2、3。但无论如何,这取决于您想要实现的目标。如果它工作一切都很好。
    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2011-06-11
    • 1970-01-01
    • 2014-12-10
    • 2014-12-19
    • 2018-09-03
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多