2012-02-20 108 views
0

我有severals標籤沒有ID,像這樣:識別每個標籤.innerhtml

<label class="optional" for="Name">Nombre</label>

我需要的是這樣的:

h=0; 

$('label').each(function(index) { 
    $(this).append('id=etiqueta'+h); 
    h=h+1; 
}); 
在文本字段

但不是。

的結果必須是這樣的:

<label class="optional" for="Name" id="etiqueta0">Nombre</label> 

非常感謝你,

問候,

阿爾瓦羅

+0

什麼是你的用例爲這個? – Quentin 2012-02-20 12:51:31

回答

1

使用您的各項指標環的指標,並給它一個id屬性:

$('label').each(function(index) { 
    $(this).attr('id', 'etiqueta'+index); 
}); 
2

你並不需要統計循環的每個迭代,你可以只使用index說法。該attr方法用於設置一個屬性的值:

$('label').each(function(index) { 
    $(this).attr('id', 'etiqueta' + index); 
}); 

其當前正在使用用於附加HTML(或文本)的元素的append方法。它不會影響該元素的屬性。

1
$('label').each(function(idx) { 
    $(this).attr('id', 'etiqueta' + idx); 
});