gpt4 book ai didi

javascript - 使用 .each 迭代具有相同类的 html 元素

转载 作者:行者123 更新时间:2023-11-28 18:22:09 24 4
gpt4 key购买 nike

我有一些具有相同类的 div 元素。我想迭代它们。我正在使用 jquery“.each”来做到这一点。我还想单独访问每个元素并切换其类,因此我需要获取类元素数组中元素的索引。我目前有一个与此类似的代码:

 $('.the_div_class').each(function(i, obj) {

if("a certain condition") {

$('.the_div_class')[0].toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;

}

}

但是我收到一条错误消息“$(...)[0].toggleClass 不是函数”。如果我不指定索引,我会遍历数组的所有元素...我 console.log “$('.the_div_class')” 数组并获得与此类似的结构:

[div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, div.the_div_class, prevObject: r.fn.init[1]]

如果我 console.log "$('.the_div_class')[0]"我得到这个:

<div class="the_div_class">

为什么它不起作用?我应该做什么才能使它起作用?

最佳答案

代码 $('.the_div_class')[0] 只会天真地获取 DOM 中与该类选择器匹配的第一个元素,它不起作用,因为它不再是jQuery 对象(因此它没有方法 .toggleClass())。在 .each() 中,您可以使用 this 来引用当前正在迭代的元素:

 $('.the_div_class').each(function(i, obj) {

if("a certain condition") {

$(this).toggleClass('other_div_class');

}

}
<小时/>

注意:要通过 jQuery 中的索引获取项目,您可以使用 .get() 。例如:

 $('.the_div_class').get(0).toggleClass('other_div_class'); 

关于javascript - 使用 .each 迭代具有相同类的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com