是否有任何简单的方法可以将数值附加到所有现有的子DOM ID,如下所述:
现有DOM:
<div class="contacts" id="contact"></div>
<div class="contacts" id="contact"></div>
<div class="contacts" id="contact"></div>
...
所需的DOM:
<div class="contacts" id="contact1"></div>
<div class="contacts" id="contact2"></div>
<div class="contacts" id="contact3"></div>
...
现有代码JS:
var additional = 0;
$(".contact").each(function() {
additional++;
$(this).prop("id", $(this).attr("id")+additional);
});
现有代码返回如下内容:
<div class="contacts" id="contact11111"></div>
<div class="contacts" id="contact2222"></div>
<div class="contacts" id="contact333"></div>
<div class="contacts" id="contact44"></div>
<div class="contacts" id="contact5"></div>
....
答案 0 :(得分:1)
获得DOM之上的唯一方法是每次添加新元素时迭代每个函数。像这样的东西:
for(i=0;i<5;i++) {
$('body').append('<div class="contacts" id="contact"></div>');
var additional = 0;
$(".contact").each(function() {
additional++;
$(this).prop("id", $(this).attr("id")+additional);
});
}
导致DOM到:
<div class="contacts" id="contact11111"></div>
<div class="contacts" id="contact2222"></div>
<div class="contacts" id="contact333"></div>
<div class="contacts" id="contact44"></div>
<div class="contacts" id="contact5"></div>
获得所需标记的正确方法是在添加所有元素时迭代元素:
for(i=0;i<5;i++) {
$('body').append('<div class="contacts" id="contact"></div>');
}//after appending 5 elements
$(".contacts").attr("id",function(index) {
return this.id + (index + 1)
});
答案 1 :(得分:0)
你只需做
$(".contact").each(function(i,item) {
//Reset Attribute id with new value
$(item).attr("id", $(item).attr("id")+(i+1));
});