我在想是否有办法找到element的属性是否包含指定值。该属性未知。如果我有这个HTML:
<input class="first" type="checkbox" data="THE-VALUE" />
<input class="second" type="checkbox" />
<input class="third" type="checkbox" name="THE-VALUE" />
我想找到属性值为 THE-VALUE 的所有输入(在本例中为.first
和.third
)。对于输入为3的情况,我不需要解决方案,但如果我有50个输入且包含THE-VALUE的属性都不同。我尝试了.attr(':contains("THE-VALUE")')
和$('input[="THE-VALUE"]')
之类的内容,但由于显而易见的原因,它无效。
所以我的问题是......有什么方法可以找到它吗?
答案 0 :(得分:6)
$("input").filter(function() {
return $.grep(this.attributes, function(arg) {
return arg.nodeValue === "THE-VALUE";
}).length > 0;
}).prop("checked", true);
DEMO: http://jsfiddle.net/7tsZN/
或作为选择器扩展名:
$.expr[':'].hasattrval = function(e, i, p) {
return $.grep(e.attributes, function(arg) {
return arg.nodeValue === p[3];
}).length;
};
$("input:hasattrval('THE-VALUE')").prop("checked", true);