jQuery:遍历元素并为子元素编号

时间:2015-07-21 21:52:36

标签: jquery loops numbers

我想对包含列表的每个span元素进行编号,始终从1开始。但现在它是连续的:

http://jsfiddle.net/QaB76/125/

标记

<li>
  <span class="1"><span>
</li>
<li>
  <span class="2"><span>
  <span class="3"><span>
</li>
<li>
  <span class="5"><span>
  <span class="6"><span>
</li>

但我希望它是:

<li>
  <span class="1"><span>
</li>
<li>
  <span class="1"><span>
  <span class="2"><span>
</li>
<li>
  <span class="1"><span>
  <span class="2"><span>
  <span class="3"><span>
</li>

感谢

1 个答案:

答案 0 :(得分:0)

each()li元素使用单独的span次迭代

&#13;
&#13;
$(document).ready(function () {
    $("li").each(function (i) {
        $(this).find("span").each(function (i) {
            $(this).attr('class', (i + 1));
        });
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul>
    <li> <span>test</span>

    </li>
    <li> <span>test</span><span>test</span>

    </li>
    <li> <span>test</span><span>test</span><span>test</span>

    </li>
</ul>
&#13;
&#13;
&#13;