2012-03-14 134 views
8

我想使用的HTML data-*屬性,並有一些像這樣的圖片:jQuery的選擇類價值

<img src="http://placehold.it/100.png" data-selected="true"> 
<img src="http://placehold.it/100.png" data-selected="false"> 
<img src="http://placehold.it/100.png" data-selected="false"> 
<img src="http://placehold.it/100.png" data-selected="true"> 
<img src="http://placehold.it/100.png" data-selected="false"> 

如何我現在僅僅只得到了那些與data-selected="true"

我想:

$("img").each(function(){ 
    if($(this)).attr("data-selected") == "true") { 
    //do something 
    } 
} 

但這似乎不是我的最佳方式。有沒有一個直接的選擇器,我可以做一些像

$("img data-selected=true") ? 

感謝您的幫助!

+1

請注意,jQuery有**優秀** [文檔](http://api.jquery.com/category/selectors/) – ManseUK 2012-03-14 20:01:04

回答

10

$("img[data-selected='true']")但引用價值不是強制性的。

PS:它被稱爲CSS attribute selector

+0

它被稱爲[屬性等於選擇器](http://api.jquery。 com/attribute-equals-selector /) – ManseUK 2012-03-14 19:58:51

3

請嘗試以下選擇

$('img[data-selected="true"]') 
7

好一件事,你應該使用.data(...)

$("img").each(function(){ 
    if($(this)).data("selected") == "true") { 
    //do something 
    } 
} 

或者你可以使用:

$("img[data-selected='true']").something... 
+0

+1指針指向'.data()'im永遠寫入'在這裏使用'.data()'而不是'.attr()'「! – ManseUK 2012-03-14 20:00:33

+0

哦,沒想過.data()會這樣做! – Bfar221 2012-03-14 20:04:35

4

您可以使用屬性選擇

$("img[data-selected='true']"); 

其他替代方案是filter()

$("img").filter(function(){ return $(this).data("selected") == "true" }); 

注意,要訪問數據屬性,你可以使用data()方法,你只要必須傳遞數據屬性名稱的後半部分。

+1

Ahhh'.filter()'!我試圖記住該功能的名稱! '+ 1' :-) – Neal 2012-03-14 20:04:07

+0

酷了很多posibilities!將嘗試這太altought第一個會更短:) – Bfar221 2012-03-14 20:08:15

3

您可以使用

$("img[data-selected='true']") 

有很多不僅僅是標籤和類的更多選擇的。見here on w3.org

+0

感謝您的鏈接! – Bfar221 2012-03-14 20:01:52

2

這是某種方式來做到這一點,而不使用jQuery:

var imgs = document.getElementsByTagName('img'); 

imgs.​​​​​map(function (img) { 
    if (img.attributes["data-selected"].value == "true") { 
     // do something 
    } 
});​ 

而且你不需要jQuery的!

+1

jQuery here'$('img')':) – ShankarSangoli 2012-03-14 20:13:12

+1

是的;但在這裏它是本地版本:'document.getElementsByTagName('img')':)並沒有更多的jQuery – 2012-03-14 20:23:18

+0

在這種情況下,它更好,如果你修改你的答案替代方法,而不使用'Javascript'。 – ShankarSangoli 2012-03-14 20:29:21