私がこれを持っている場合:
<span data-helo="1">something</span>
<span data-helo="2">something different</span>
最初のスパンをターゲットにしたいのですが、どうすればいいですか?
私は次のようなものを試しました:
$('span').data('helo', '1')
しかし、両方のスパンが返されました。
私がこれを持っている場合:
<span data-helo="1">something</span>
<span data-helo="2">something different</span>
最初のスパンをターゲットにしたいのですが、どうすればいいですか?
私は次のようなものを試しました:
$('span').data('helo', '1')
しかし、両方のスパンが返されました。
試す:
$('span[data-helo="1"]')
これは、 value の -attribute を持つすべての -elements をターゲットにspan
します。data-helo
1
あなたのコードで:
$('span').data('helo', '1')
すべての要素をターゲットにして、それらの属性を にspan
設定しています。そして、そのコレクションを返します (典型的な jQuery チェーンを介して)。data-helo
1
あなたは試すことができeq()
ますdata()
:
$('span:eq(0)').data('helo'); // returns "1"
$('span:eq(1)').data('helo'); // returns "2"
属性で要素を選択する場合は、属性セレクターを使用できます。
$('span[data-helo="1"]') // selects spans which has attribute "data-helo" and it's value is "1"
$('span[data-helo="2"]')
また:
$('span[data-helo]:eq(0)') // first span element that has a data-helo attribute
$('span[data-helo]:eq(1)') // second span element that has a data-helo attribute
私はそれがあなたが望むものだと思います
$('span[data-helo=1]')