【问题标题】:Iterate over html elements with same class using .each使用 .each 迭代具有相同类的 html 元素
【发布时间】:2016-09-28 03:36:54
【问题描述】:

我有一些具有相同类的 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">

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

【问题讨论】:

    标签: javascript jquery html arrays


    【解决方案1】:

    代码$('.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'); 
    

    【讨论】:

      【解决方案2】:

      将您的代码更改为:

      var collection = $('.the_div_class');
      collection.each(function(i, obj) {
      
         if("a certain condition") {
            $(collection[0]).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
         }
      }
      

      您需要通过再次将 DOM 元素传递给 $ 来重新创建 jQuery 对象,即您的代码为 $($('.the_div_class')[0])。

      【讨论】:

        【解决方案3】:

        当您指定索引时,您获取的是使用 jQuery 选择的纯 javascript 元素,而不是 jQuery 对象。这就是您无法使用 toggleClass() 方法的原因。

        您可以像这样将其包装在 jQuery 中 $($(selector)[i]) 以将其转换回 jQuery 对象。但是,每个循环提供的参数在这里是你的朋友。也就是说,你可以用$(obj)访问循环中的当前对象。

        【讨论】:

          【解决方案4】:

          您需要更改代码以使用此关键字获取元素:

          $('.the_div_class').each(function(i, obj) {
             if("a certain condition") {
              $(this).toggleClass('other_div_class'); // trying to access the index 0 of the array that contains the elements of that class;
             }
           }
          

          【讨论】:

            猜你喜欢
            • 2021-09-13
            • 1970-01-01
            • 1970-01-01
            • 2017-06-13
            • 1970-01-01
            • 2016-03-03
            • 1970-01-01
            • 2014-07-13
            相关资源
            最近更新 更多