2012-07-11 58 views

回答

5

嘗試:

$('span[data-helo="1"]') 

這將針對所有span -elements與data-helo -attribute的價值1

http://jsfiddle.net/F2NUk/

與您的代碼:

$('span').data('helo', '1') 

你的目標都span -elements及其data-helo屬性設置爲1。然後返回該集合(通過典型的jQuery鏈接)。

1

試試這個,

Live Demo

對於分配

$('span').attr('data-helo', '2'); 

對於選擇

$('span[data-helo=2]') 

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 

http://api.jquery.com/category/selectors/

1

我認爲這是你想要的

$('span[data-helo=1]')