小编web*_*kie的帖子

循环遍历div(包括孩子)中的所有div

我让这个页面的静态版本在本地工作得很好,但我公司使用的CMS在CMS中实现时会发出可怕的代码.

最初我试图循环遍历div中的所有div并构建一个包含结果的选择框.

<div id="products-list">
  <div id="glasgow">
      <div class="product">
        <!--Content-->
      </div>
  </div>

  <div id="edinburgh">
      <div class="product">
        <!--Content-->
      </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用一个简单的每个循环与第一级div是好的.

 $("#products-list > div").each(function() {
        if ($(this).attr("id") != undefined || $(this).attr("id") != null) {
            $('#select-example').append($('<option>', {
                value: $(this).attr("id"),
                text: $(this).attr("id")
            }));
        }
    });
Run Code Online (Sandbox Code Playgroud)

但是我的CMS决定像这样包装div,而且我无能为力.我正在尝试返回ID"Glasgow"和"Edinbugh".

<div id="products-list">
  <div class="w-component-wrapper">
    <div>
      <div class="w-component-content">
        <div id="glasgow">
          <div class="product">
            <!-- Content --> 
          </div> 
        </div>
      </div>
    </div>
  </div>

  <div class="w-component-wrapper">
    <div>
      <div class="w-component-content">
        <div id="edinburgh">
          <div class="product">
            <!-- Content --> 
          </div> 
        </div>
      </div>
    </div>
  </div>
</div> …
Run Code Online (Sandbox Code Playgroud)

html javascript each jquery loops

1
推荐指数
1
解决办法
996
查看次数

标签 统计

each ×1

html ×1

javascript ×1

jquery ×1

loops ×1