0

このような複数のインスタンスを処理する方法が正確にはわかりません。通常の JS では [0] などを簡単に使用できることを知っています。

私のコードはこれです:

location.href = $('a.test').attr('href');

テストの最初のインスタンスと 2 番目のインスタンスの両方を処理する必要があります。簡単なものはありますか

location.href = $('a.test')[0].attr('href');

私が行方不明ですか?

4

4 に答える 4

2
location.href = $('a.test').eq(0).attr('href');

またはあなたが試すことができます

location.href = $('a.test:eq(0)').attr('href');

eq():eq()attrを参照

于 2013-10-05T04:22:33.743 に答える
2

$('a.test')[0]method を持たないdom要素参照を返すattr()ため、スクリプトは失敗します

.eq(インデックス) を使用

location.href = $('a.test').eq(0).attr('href');

また

location.href = $('a.test:eq(0)').attr('href');
于 2013-10-05T04:19:50.117 に答える
2

インデクサーが DOM オブジェクトを返すため、jQuery オブジェクトを使用する代わりに、javascript DOM オブジェクトで attr を呼び出そうとしていますeq()を使用して jQuery オブジェクトを取得します

location.href = $('a.test').eq(0).attr('href');

attr の代わりに href で DOM オブジェクトを使用できます

location.href = $('a.test')[0].href;
于 2013-10-05T04:19:53.537 に答える
1

このデモが役立つかもしれません:作業デモ http://jsfiddle.net/CmQGu/

nth-childここで API デモを使用することもできます: http://jsfiddle.net/wYdyJ/

デモで示したように、これにはさまざまな方法があります。また、これを熱心に読んでいる場合: .eq() と .get() と :nth-child() の違い?

API:

コード:

alert(location.href = $('a.test').eq(0).attr('href'));

alert(location.href = $('a.test').first().attr('href'));

alert(location.href = $('a.test:nth-child(2)').attr('href'));

それが役に立てば幸い:)

于 2013-10-05T04:23:28.887 に答える