【问题标题】:appending an incrementing number inside each div element在每个 div 元素内附加一个递增的数字
【发布时间】:2012-08-13 16:29:39
【问题描述】:

我有一个包含多个 div 的页面,我想在每个 div 中添加一个递增的数字。

我认为这可以完成这项工作,但事实并非如此:

$(document).ready(function(){
    var i;
    while ( i<count) {
        $('#div').append(i);
        i++;
    }
});

我在&lt;/body&gt;之后添加了这个脚本

【问题讨论】:

  • 你想要一个递增的 id 吗?
  • @RobinMaben 你能闻到吗?很棒
  • 对不起,忘了说 var count=0;

标签: javascript jquery numbers


【解决方案1】:
$(function(){
    $('div').slice(0, count).each(function(i){
       $(this).append(i+1);
    });
});​

.slice() 用于选择前 n 个匹配的元素(如 i &lt; count 所建议的那样)。 请参阅this post 了解更多信息。

DEMO here


另外..

如果你的 div(或任何元素)是彼此的兄弟,你可以使用更优雅的..

$('mySelector').each(function(){ $(this).append($(this).index()) });

【讨论】:

    【解决方案2】:

    这是一种方法:

    ​$("div").each(function(i){
        $(this).append(i);
    });​​​
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      相关资源
      最近更新 更多