2014-01-09 60 views
0

我正在尋找獲取div的實例編號,例如:我有.test div的4個實例,並且使用.length只生成4。但是我想在每個div中放入實例編號,例如.test div的第三個實例中將包含3等等。

的jsfiddle演示:http://jsfiddle.net/neal_fletcher/YrtjF/

HTML:jQuery:獲取div實例編號

<div class="test"></div> 
<div class="test"></div> 
<div class="test"></div> 
<div class="test"></div> 

的jQuery:

$(document).ready(function() { 

    var n = $(".test").length; 

    $('.test').html(n); 

}); 

如果這是在所有可能的?任何建議將不勝感激!

回答

12

使用html()的版本,需要一個函數作爲參數

$('.test').html(function (i) { 
    return i + 1 
}); 

演示:Fiddle

+0

你的實際上更好... rs – LcSalazar

1
$(document).ready(function() { 

var n = 1; 
$('.test').each(function() { 
    $(this).html(n); 
    n++; 
}); 

}); 
1

您可以使用此

$(document).ready(function() {  
    $(".test").html(function(i,v){ 
     return i+1; 
    });  
}); 

DEMO

0

你可以使用這裏的每種方法

$(document).ready(function() { 
    $(".test").each(function(i){ 
    $(this).html(i +1); 
    }); 
});