使用jquery动态地将div id添加到class元素

时间:2015-02-16 08:00:48

标签: 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> 

这些是地图生成的div,它包含相同的类 为leaflet-marker-icon。对于每个div,我想添加一个id属性,其中包含唯一的Ex {id=0id=1id=2id=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)是一个类。 任何人都可以建议如何在课堂上添加唯一的ID。

6 个答案:

答案 0 :(得分:4)

继续您的解决方案:( 我不知道为什么人们会尝试展示他们所知道的并且不会纠正您

试试这个:

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

答案 1 :(得分:1)

在for循环中使用:eq选择器。

$('.leaflet-marker-icon:eq(' + x + ')').attr('id', x);

答案 2 :(得分:1)

由于您的选择器是类,因此您应该知道它返回一个集合。所以在你的情况下你可以使用它:

$('.leaflet-marker-icon').attr('id', function(i) {
  return i;
});

当您使用jquery并为元素设置唯一ID时,可以使用.attr('attribute', fn)

$('.leaflet-marker-icon').attr('id', function(i) {
  return i;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="leaflet-marker-icon">leaflet-marker-icon1</div>
<div class="leaflet-marker-icon">leaflet-marker-icon2</div>
<div class="leaflet-marker-icon">leaflet-marker-icon3</div>
<div class="leaflet-marker-icon">leaflet-marker-icon4</div>

答案 3 :(得分:0)

您可以使用.each()迭代元素并使用元素上下文(this)来设置其属性值:

$('.leaflet-marker-icon').each(function(i){
  this.id=i;
});

Working Demo

答案 4 :(得分:0)

您应该在动态添加id时添加div,这样可以减少工作量。但如果你不能这样做,那么试试下面的代码

var count = 1;
$('.leaflet-marker-icon').each(function(){
  $(this).attr('id',count);
  count++;
});

根据Royi Namir的建议,以下是实现解决方案的另一种方法

$('.leaflet-marker-icon').each(function(i,n){
      $(this).attr('id',i);
 });

答案 5 :(得分:0)

创建变量并将其设置为零。使用each()函数,添加等于此变量的id属性,并将变量增加1,以便分配给下一个元素。

检查div元素的结果:

&#13;
&#13;
$(document).ready(function() {
  //var i = 0;
  $('.leaflet-marker-icon').each(function(i) {
    $(this).attr('id', i);
    //i++;
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="leaflet-marker-icon">1</div> 
 <div class="leaflet-marker-icon">2</div> 
 <div class="leaflet-marker-icon">3</div> 
<div class="leaflet-marker-icon">4</div>
&#13;
&#13;
&#13;

相关问题