2

我有同一个类的三个元素:

<div class="hotel_price">30.00</div>
<div class="hotel_price">35.00</div>
<div class="hotel_price">36.00</div>

我的功能:

<script>
  $(document).ready(function() {
    for(i=1;i<=3;i++){ $('.hotel_price').attr('id','hotel_'+i);}
  });
</script>

结果:

<div id="hotel_3" class="hotel_price">30.00</div>
<div id="hotel_3" class="hotel_price">35.00</div>
<div id="hotel_3" class="hotel_price">36.00</div>

我需要:

 <div id="hotel_1" class="hotel_price">30.00</div>
    <div id="hotel_2" class="hotel_price">35.00</div>
    <div id="hotel_3" class="hotel_price">36.00</div>
4

5 回答 5

8

你要:

$('.hotel_price').attr('id', function(i) { return 'hotel_' + i; });

您的代码不起作用的原因是您每次通过循环设置所有 3 个元素的 ID:

for(i=1;i<=3;i++) {
   // at this point, there is nothing specifying which .hotel_price to modify
   // so all 3 of them will be changed each time around
   // using .attr(name, fn) or .each(fn) is the jQuery way to do this.
   $('.hotel_price').attr('id','hotel_'+i);
}
于 2013-05-20T15:55:58.743 回答
1

您想使用该each()函数来迭代元素。

$('.hotel_price').each(function(i) {
    $(this).attr('id', 'hotel_' + i);
});
于 2013-05-20T15:55:55.773 回答
0

当您编写时,$('.hotel_price').attr(...)您正在设置与选择器匹配的所有元素的属性。您需要遍历元素,依次对每个元素进行操作,以便为每个元素分配不同的属性。jQuery 的each()方法用于此目的。

var i = 1;
$('.hotel_price').each(function() {
    $(this).attr('id','hotel_'+i);
    i++;
});
于 2013-05-20T15:56:08.130 回答
0
$(document).ready(function () {
    $('div.hotel_price').each(function (ctr) {
         $(this).attr('id', 'hotel_' + (ctr +1));
     });
});
于 2013-05-20T15:56:10.850 回答
-1

使用 jQuery 的.eq()

$(document).ready(function() {
    for(i=1;i<=3;i++){ $('.hotel_price').eq(i-1).attr('id','hotel_'+i); }
});
于 2013-05-20T15:57:13.690 回答