0

次のマークアップをお願いします。

<div class="closet">
   <input name="hello1" class="input" />
</div>


<div class="closet">
   <input  name="hello2" class="input" />
</div>

入力名に属性を付けて別の値(例:hello5とhello6)を設定したいので、これが私のコードです:

var i = 5;
$('.closet').each(function (k) 
{
    i++;

   $('.input').attr('name', 'hello'+i);
});

しかし、それが両方の入力に対して私に与えた問題は、値「hello6」です。

何かアドバイスはありますか?

4

3 に答える 3

2

交換

$('.input').attr('name', 'hello'+i);

$('.input', this).attr('name', 'hello'+i);

したがって、反復が行われて.inputいるの中にあるものを変更します。.closet

于 2012-12-09T18:38:45.597 に答える
0

each()ループ内のインデックスと要素の両方にすでにアクセスできます。

$('.closet').each(function(index, elem)  {
   $('.input', elem).attr('name', 'hello'+(index+5));
});
于 2012-12-09T18:40:06.280 に答える
0

それ以外の

$('.input').attr('name', 'hello'+i);

する必要があります

$(this).find('.input').attr('name', 'hello'+i);
于 2012-12-09T18:40:33.380 に答える