<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>...
请帮忙
答案 0 :(得分:0)
您要做的是根据父(id
)元素的索引(基于兄弟姐妹)生成.sp_main
$(".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;