admin管理员组文章数量:1431522
I'm looking to get the instance number of a div, e.g. I have 4 instances of the .test
div, and using .length
just generates 4
. But I want to put the instance number in each div, for example the 3rd instance of the .test
div would have a 3
in it and so on.
jsFiddle demo: /
HTML:
<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);
});
If this is at all possible? Any suggestions would be greatly appreciated!
I'm looking to get the instance number of a div, e.g. I have 4 instances of the .test
div, and using .length
just generates 4
. But I want to put the instance number in each div, for example the 3rd instance of the .test
div would have a 3
in it and so on.
jsFiddle demo: http://jsfiddle/neal_fletcher/YrtjF/
HTML:
<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);
});
If this is at all possible? Any suggestions would be greatly appreciated!
Share Improve this question asked Jan 9, 2014 at 17:04 user1374796user1374796 1,58213 gold badges46 silver badges76 bronze badges4 Answers
Reset to default 12Use the version of html() that takes a function as the parameter
$('.test').html(function (i) {
return i + 1
});
Demo: Fiddle
$(document).ready(function () {
var n = 1;
$('.test').each(function() {
$(this).html(n);
n++;
});
});
You can use this
$(document).ready(function () {
$(".test").html(function(i,v){
return i+1;
});
});
DEMO
you can use each method here
$(document).ready(function () {
$(".test").each(function(i){
$(this).html(i +1);
});
});
本文标签: javascriptjQuery get div instance numberStack Overflow
版权声明:本文标题:javascript - jQuery: get div instance number - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745470911a2659743.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论