2015-07-20 82 views
1
<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 =「跨度+長」到 預期輸出的孩子跨度是像下面的jQuery基於元素長度元素添加ID

<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

那你的錯誤是什麼? – Varun

回答

0

你要做的是根據父母(.sp_main)元素的索引(基於兄弟姐妹)生成id

$(".span_group .sp_main span").attr('id', function(index) { 
 
    return "span" + ($(this).parent().index() + 1); 
 
});
<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>