2012-03-14 86 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