【问题标题】:Iteration in JQueryJQuery 中的迭代
【发布时间】:2010-11-06 15:11:00
【问题描述】:

我是 jQuery 新手。

我的代码中有一个变量增量,它显示面板中有多少个 div。

我想遍历这些 div 以获取标签的属性、输入类型、每个 div 内所有内容的大小。

从 1 开始,我想迭代到增量 .. 我如何在 JQUery 中这样做?请给我一个建议。

【问题讨论】:

    标签: jquery iterator foreach


    【解决方案1】:

    如果您想在 JQuery 中遍历面板中的所有 div,那么最简单的方法就是执行以下操作:

    $("#panel div").each(function() { 
      // $(this) refers to the div
    }
    

    如果您想将其限制为前 N 个 div,那么有很多方法可以做到这一点:

    $("#panel div:lt(" + (N+1) + ")").each(function() { 
      // limits to the only those div's less than N+1.
    }
    

    【讨论】:

      【解决方案2】:

      我会同意 samjudson 所说的话,但需要更详细一点。

      首先,选择器“#panel div”获取元素中 ID 为“panel”的所有 div,这听起来像是您想要的。然后,使用 jQuery 的 'each' 函数,您可以调用任意函数,将每个 div 绑定到 'this' 项。

      所以在函数中,“this”实际上是 DOM 中每个 div 的项目。通过引用 $(this),您可以获得 jQuery 在项目上交互的强大功能 - 但如果您只需要 DOM 项目本身的裸属性,您可以直接从 'this' 获取它们。

      $('#panel div').each(function(i) {
          // 'this' is the div, i is an incrementing value starting from 0,
          // per zero-based JS norms
          // If you're going to do a lot of jQuery work with the div,
          // it's better to make the call once and save the results - more efficient
          var $this = $(this);
      
          // If you want to get out before you're done processing,
          // simply return false and it'll stop the looping, like a break would
          if (i > 4) { return false; }
      
          // Look up the labels inside of the div
          // Note the second argument to the $ function,
          // it provides a context for the search
          $("label", this).each(function(){
              // 'this' is NOW each label inside of the div, NOT the div
              // but if you created a $this earlier, you can still use it to get the div
              // Alternately, you can also use $(this).parent()
              // to go up from the label to the div
          });
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-13
        • 2010-12-14
        • 2012-10-17
        • 2014-10-17
        • 2012-06-23
        • 2011-04-07
        • 2013-01-27
        相关资源
        最近更新 更多