2011-08-09 15 views
0

我有一个未知的号码部分的元件中的每个元素:增量属性值(INT),用于使用jquery

<section id="foo"> 
... 
</section> 

<section id="bar"> 
... 
</section> 

对于其存在我需要添加属性“数据串行”,这是一个每部整数从0开始和以1为每个部分存在递增,例如上面会变成:

<section id="foo" data-serial="0"> 
... 
</section> 

<section id="bar" data-serial="1"> 
... 
</section> 

<section id="bla" data-serial="2"> 
... 
</section> 
... 

我怎样才能实现这一点使用jQuery?

由于

回答

10
var current = 0; 
$("section").each(function() { 
    $(this).data("serial", current); 
    current++; 
}); 

此遍历文档中的所有section的元件,并且current值附接至使用jQuery data方法的每个元素。

0

var i = 0; 
$('section').each(function() { 
    $(this).data('serial', i++); 
}); 
1
$("section").each(function(i, e) { $(e).attr("data-serial", i) }); 
11

詹姆斯·阿勒代斯的回答采取每个传递给它被赋予的功能很少使用的参数的优势的修改版本。第一个参数是循环当前迭代的索引。

http://api.jquery.com/each/

$("section").each(function(index) { 
    $(this).attr("data-serial", index); 
}); 
+0

啊善于思考! +1 –

+0

大家总是忘记那些可怜的小参数。很高兴看到它用于改变。 ;-) – Chris

+0

是的,jQuery的奇迹,使得一切都比你想象的要简单! –