javascript - 使用jquery动态添加div id到类元素

标签 javascript jquery css

<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);
    }

示例:http://jsbin.com/vuzuhe/2/edit

关于javascript - 使用jquery动态添加div id到类元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536878/

相关文章:

javascript - 从 JSON 中的 servlet 请求获取纬度和经度并在谷歌地图对象中打印出来

javascript - 添加事件监听器而不覆盖

html - 如何在之前的背景图片之上添加背景图片?

javascript - 如何在 extjs2 中获取具有相同名称的多个文本字段的值

javascript ImageData复制或移动性能

javascript - 居中的内联文本在淡入时重新定位

css - 使两个百分比的 div 响应

html - 什么 CSS 样式可以在超链接之间提供更多空间

javascript - 如何使用 Protractor 检查类名的变化

javascript - 单击时添加图像 - 仅添加一次然后停止