【问题标题】:jQuery to loop through elements with the same classjQuery循环遍历具有相同类的元素
【发布时间】:2011-06-11 17:50:52
【问题描述】:

我有一大堆带有 testimonial 类的 div,如果特定条件为真,我想使用 jquery 循环遍历它们以检查每个 div。如果是真的,它应该执行一个动作。

有人知道我会怎么做吗?

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    使用每个:'i' 是数组中的位置,obj 是您正在迭代的 DOM 对象(也可以通过 jQuery 包装器 $(this) 访问)。

    $('.testimonial').each(function(i, obj) {
        //test
    });
    

    查看api reference了解更多信息。

    【讨论】:

    • 带i、obj参数的函数帮助很大。如果只使用 each,那么它就不会迭代。
    • @Darwindeeds 正确!实际迭代器使用该函数来处理每个项目。返回false 将停止迭代。
    • 值得指出的是,“obj”将是dom对象,而$(this)是jQuery对象。
    • 我们不能用 jQuery(this 'ul li').length 来获取元素 ul li 的长度吗?
    • +1 用于建议 $(this) 访问对象... obj 作为 DOM 对象不允许直接附加函数,例如 obj.empty()
    【解决方案2】:

    试试这个...

    $('.testimonial').each(function(){
        //if statement here 
        // use $(this) to reference the current div in the loop
        //you can try something like...
    
    
        if(condition){
    
        }
    
    
     });
    

    【讨论】:

    • 仅供参考:break; 不会中断。你必须使用return false;
    【解决方案3】:

    现在不用 jQuery 也很简单。

    没有 jQuery:

    只需选择元素并使用.forEach() method 对其进行迭代:

    const elements = document.querySelectorAll('.testimonial');
    Array.from(elements).forEach((element, index) => {
      // conditional logic here.. access element
    });
    

    在旧版浏览器中:

    var testimonials = document.querySelectorAll('.testimonial');
    Array.prototype.forEach.call(testimonials, function(element, index) {
      // conditional logic here.. access element
    });
    

    【讨论】:

      【解决方案4】:

      试试这个例子

      HTML

      <div class="testimonial" data-index="1">
          Testimonial 1
      </div>
      <div class="testimonial" data-index="2">
          Testimonial 2
      </div>
      <div class="testimonial" data-index="3">
          Testimonial 3
      </div>
      <div class="testimonial" data-index="4">
          Testimonial 4
      </div>
      <div class="testimonial" data-index="5">
          Testimonial 5
      </div>
      

      当我们想要访问那些data-index 大于2divs 时,我们需要这个jquery。

      $('div[class="testimonial"]').each(function(index,item){
          if(parseInt($(item).data('index'))>2){
              $(item).html('Testimonial '+(index+1)+' by each loop');
          }
      });
      

      Working example fiddle

      【讨论】:

        【解决方案5】:

        你可以这样做

        $('.testimonial').each(function(index, obj){
            //you can use this to access the current item
        });
        

        【讨论】:

          【解决方案6】:

          jQuery's .eq()可以帮助你用索引的方式遍历元素。

          var testimonialElements = $(".testimonial");
          for(var i=0; i<testimonialElements.length; i++){
              var element = testimonialElements.eq(i);
              //do something with element
          }
          

          【讨论】:

          • 这确实是最有效的方法。
          【解决方案7】:
          divs  = $('.testimonial')
          for(ind in divs){
            div = divs[ind];
            //do whatever you want
          }
          

          【讨论】:

          • 虽然没有给你 jquery 对象,只是 dom 元素
          • @celwell 不能指望 jQuery 为您做所有事情。只需制作自己的 jQuery 对象$(ind)
          【解决方案8】:

          您可以使用.filter 简洁地做到这一点。以下示例将隐藏所有包含“某物”一词的 .testimonial div:

          $(".testimonial").filter(function() {
              return $(this).text().toLowerCase().indexOf("something") !== -1;
          }).hide();
          

          【讨论】:

            【解决方案9】:

            使用简单的 for 循环:

            var testimonials= $('.testimonial');
            for (var i = 0; i < testimonials.length; i++) {
              // Using $() to re-wrap the element.
              $(testimonials[i]).text('a');
            }
            

            【讨论】:

              【解决方案10】:

              我可能遗漏了部分问题,但我相信您可以这样做:

              $('.testimonial').each((index, element) => {
                  if (/* Condition */) {
                      // Do Something
                  }
              });
              

              这里使用jQuery的each方法:https://learn.jquery.com/using-jquery-core/iterating/

              【讨论】:

                【解决方案11】:

                没有更新 jQuery

                document.querySelectorAll('.testimonial').forEach(function (element, index) {
                    element.innerHTML = 'Testimonial ' + (index + 1);
                });
                <div class="testimonial"></div>
                <div class="testimonial"></div>

                【讨论】:

                • 几乎相同的答案已经在这里,我认为你应该编辑现有的
                【解决方案12】:
                $('.testimonal').each(function(i,v){
                  if (condition) {
                    doSomething();
                  }
                });
                

                【讨论】:

                  【解决方案13】:

                  在 JavaScript ES6 .forEach()Element.querySelectorAll() 给出的类数组 NodeList collection

                  document.querySelectorAll('.testimonial').forEach( el => {
                    el.style.color = 'red';
                    console.log( `Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );
                  });
                  <p class="testimonial" id="1">This is some text</p>
                  <div class="testimonial" id="2">Lorem ipsum</div>

                  【讨论】:

                  • 不需要扩展运算符 + 数组表示法,肯定做 doc..torAll.forEach() 就足够了吗?
                  • 谢谢。绝对地。 [...ArrayLike] 用于 querySelectorAll 不支持 .forEach 的时间。 @aabbccsmith
                  【解决方案14】:

                  更准确:

                  $.each($('.testimonal'), function(index, value) { 
                      console.log(index + ':' + value); 
                  });
                  

                  【讨论】:

                  • 如果您喜欢从更实用的角度阅读/写作,这很好。
                  【解决方案15】:

                  您可以使用 jQuery 的 $each 方法循环遍历所有带有类证明的元素。 i => 是集合中元素的索引,val 为您提供该特定元素的对象,您可以使用“val”进一步访问元素的属性并检查您的条件。

                  $.each($('.testimonal'), function(i, val) { 
                      if(your condition){
                         //your action
                      }
                  });
                  

                  【讨论】:

                    猜你喜欢
                    • 2016-04-26
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-10-20
                    • 2013-04-11
                    • 2010-09-15
                    • 1970-01-01
                    相关资源
                    最近更新 更多