最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: get div instance number - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 12

Use 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);
    });
});
发布评论

评论列表(0)

  1. 暂无评论