通过jquery基于元素长度向元素添加id

时间:2015-07-20 12:26:59

标签: jquery

<div class="span_group">
<span class="sp_main"><span>Sample text</span></span>
<span class="sp_main"><span>Sample text</span></span>
<span class="sp_main"><span>Sample text</span></span>
<span class="sp_main"><span>Sample text</span></span>
<span class="sp_main"><span>Sample text</span></span>
</div>
$(".span_group .sp_main span").each(function(index){
    $(this).attr("id","span"+$(this).children("span").length); 
});

我试图将id =“span + length”添加到子跨度 预期产出如下

<span class="sp_main"><span id="span1">Sample text</span></span>
<span class="sp_main"><span id="span2">Sample text</span></span>
<span class="sp_main"><span id="span3">Sample text</span></span>...

请帮忙

1 个答案:

答案 0 :(得分:0)

您要做的是根据父(id)元素的索引(基于兄弟姐妹)生成.sp_main

&#13;
&#13;
$(".span_group .sp_main span").attr('id', function(index) {
  return "span" + ($(this).parent().index() + 1);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="span_group">
  <span class="sp_main"><span>Sample text</span></span>
  <span class="sp_main"><span>Sample text</span></span>
  <span class="sp_main"><span>Sample text</span></span>
  <span class="sp_main"><span>Sample text</span></span>
  <span class="sp_main"><span>Sample text</span></span>
</div>
&#13;
&#13;
&#13;