【问题标题】:jQuery loop though two levels of elementsjQuery 循环遍历两级元素
【发布时间】:2010-10-28 22:15:28
【问题描述】:

我有一些看起来像这样的 html:

<div class="block">
    <div id="item1"></div>
    <div id="item2"></div>
</div>

<div class="block">
    <div id="item3"></div>
</div>

我正在尝试检查我的 div 是否包含特定元素。我需要遍历每个块,然后获取每个项目。

到目前为止我得到了什么

    $('.block:has(div)').each(function() {
            // do something with the block
    });

这很棒,因为它将返回所有包含项目的块。但我需要一些类似的东西

    $('.block:has(div)').each(function() {
             $('current place in loop' + li).each(function() {
                    // do something with each item element, before the block loop has finished
             });
    });

有什么想法吗?

【问题讨论】:

    标签: jquery html loops foreach


    【解决方案1】:

    我希望你是这个意思:

    $('.block').each(function(){
        $(this).find('div').each(function(){
            //do your stuff
        });
    });
    

    【讨论】:

    • 是的,这正是我的意思,按我的想法工作:)
    • 请注意,这将在任何级别找到父元素下的所有
      元素。使用 children() 仅获取直接子级。
    【解决方案2】:

    我不能 100% 确定这是否能回答您的问题,但以下方法不起作用:

    $('.block:has(div)').each(function() {
      $(this).children('div').each(function() {
        // do something with each item element, before the block loop has finished
      });
    });
    

    【讨论】:

      【解决方案3】:

      我会在嵌套的 each 中构建选择器,或者使用 find:

       $('.block:has(div)').each(function() {
           $('#' + this.id +  ' li').each(function() {
               //do stuff on list item            
           });
       });
      

       $('.block:has(div)').each(function() {
           $(this).find('li').each(function() {
               //do stuff on list item            
           });
       });
      

      【讨论】:

        【解决方案4】:

        你尝试过使用

        $("#" + this)
        

        ?
        它主要用于jquery文档的每个示例 (harshath 已经发帖了……太慢了,呜咽

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-15
          • 2018-04-13
          • 2018-06-05
          • 2013-07-22
          • 1970-01-01
          • 1970-01-01
          • 2010-12-20
          相关资源
          最近更新 更多