2

同じクラスの要素が 3 つあります。

<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 に答える