javascript 计算所有 div 元素并使用 jQuery 在跨度内添加每个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18235548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:09:18  来源:igfitidea点击:

Count all div elements and add each number inside span using jQuery

javascriptjqueryhtml

提问by Jim

I need to show each number of div in the page in order

我需要按顺序显示页面中的每个div数

And add the value of each div inside span

并在 span 内添加每个 div 的值

so if I have 4 divs inside page like this

所以如果我在页面内有 4 个 div 像这样

<div>first div</div>
<div>second div</div>
<div>third div</div>

every div need to show his order and be like this

每个div都需要显示他的顺序并像这样

<div>first div <span>1</span></div>
<div>second div <span>2</span></div>
<div>third div <span>3</span></div>

This html example code in jsfiddle

jsfiddle 中的此 html 示例代码

http://jsfiddle.net/CtDLe/

http://jsfiddle.net/CtDLe/

I need the output to be like this using jQuery

我需要使用 jQuery 输出像这样

http://jsfiddle.net/CtDLe/1/

http://jsfiddle.net/CtDLe/1/

回答by tymeJV

Simple eachloop does the trick:

简单的each循环可以解决问题:

$("div").each(function(i) {
    $(this).find("span").text(++i);
});

Demo: http://jsfiddle.net/CtDLe/3/

演示:http: //jsfiddle.net/CtDLe/3/

回答by Stephen Thomas

$("div").each(function(idx,elem) {
    $("<span>").text(idx).appendTo(wherever);
});

回答by Amin Abu-Taleb

You can try this:

你可以试试这个:

$("div").each(function(i, elem){
 $(elem).append($("<span>"+(i+1)+"</span>"));
});

JSFiddle example

JSFiddle 示例

回答by j08691

var counter = 1;
$('h1').each(function () {
    $(this).find('span').html(counter);
    counter++;
});

jsFiddle example

jsFiddle 示例