Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery和输出对div进行计数_Jquery_Count - Fatal编程技术网

使用jquery和输出对div进行计数

使用jquery和输出对div进行计数,jquery,count,Jquery,Count,我想用“.item”类自动计算div的数量。之后,我希望jQuery在.item中的另一个div中输出编号,并使用类“.itemnumber”。所以我希望第一个div输出“1”,第二个div输出“2”,依此类推。我知道如何计数,但我不知道如何为earch div.输出数字 感谢您的帮助 你好吗 <div class="item"> <div class="itemnumber"></div> </div> <div class="it

我想用“.item”类自动计算div的数量。之后,我希望jQuery在.item中的另一个div中输出编号,并使用类“.itemnumber”。所以我希望第一个div输出“1”,第二个div输出“2”,依此类推。我知道如何计数,但我不知道如何为earch div.输出数字

感谢您的帮助

你好吗

<div class="item">
   <div class="itemnumber"></div>
</div>

<div class="item">
   <div class="itemnumber"></div>
</div>
可能有更优化的解决方案,但请尝试以下方法:

var count = $('div.item').length; //Get all items with class "div", which returns an array... so you just use the "length" to get the total count.

$('div.item').each(function(k,v){ //.each takes a first argument which is a function, and this function takes 2 arguments "k"ey and "v"alue.
    //v in this case is the div, so:
    $('.itemnumber',v).html('Div #' + String(k+1));
});
如果有任何疑问,请告诉我


干杯

这完全成功了!太棒了,谢谢你。你还知道如何在前9项前加上“0”吗。所以我得到01,02。。。08、09、10、11很高兴它成功了。至于填充数字,最快的解决方案是实现这个功能:但是,我建议您使用PHPJS.org的str_pad函数,如下所示:这将允许您使用str_pad的全部功能,而不仅仅是两位数。干杯顺便说一句,请记住var“count”根本没有被使用,我只是把它放在那里,以防您想事先知道类为“item”的div的总量。
var count = $('div.item').length; //Get all items with class "div", which returns an array... so you just use the "length" to get the total count.

$('div.item').each(function(k,v){ //.each takes a first argument which is a function, and this function takes 2 arguments "k"ey and "v"alue.
    //v in this case is the div, so:
    $('.itemnumber',v).html('Div #' + String(k+1));
});