<div class="leaflet-marker-icon"></div>
<div class="leaflet-marker-icon"></div>
<div class="leaflet-marker-icon"></div>
<div class="leaflet-marker-icon"></div>
这些是由 map 生成的 div,它包含相同的类
作为 leaflet-marker-icon
。我想为每个 div 添加一个 id
具有唯一 Ex 的属性 (id=0
, id=1
, id=2
, id=3
);
我的代码是:
var length = $('.leaflet-marker-icon').length;
for (var x = 0; x < length; x++) {
$('.leaflet-marker-icon').attr('id', x);
}
在 for 循环中它总是采用相同的 id 因为 $('.leaflet-marker-icon').attr('id', x)
是一个类。
任何人都可以建议如何向类(class)添加唯一 ID。
最佳答案
要继续您的解决方案:(我不明白为什么人们试图展示他们所知道的而不是纠正您)
试试这个:
var _=$('.leaflet-marker-icon'); //let's cache the array
var length = _.length; //let's cache the length
for(var x=0; x<length; x++) {
_.eq(x).prop('id', x);
}
关于javascript - 使用jquery动态添加div id到类元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536878/