是否有一种简单直接的方法来根据元素的数据属性选择元素?例如,选择所有具有customerID值为22的数据属性的锚。

我有点犹豫是否要使用rel或其他属性来存储此类信息,但我发现根据存储的数据选择元素要困难得多。


当前回答

对于那些在谷歌上搜索并想要使用数据属性进行选择的更通用规则的人:

$("[data-test]")将选择任何仅具有data属性的元素(无论属性的值是多少)。包括:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>

$('[data-test~="foo"]')将选择任何数据属性包含foo但不必精确的元素,例如:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>

$('[data-test="the_exact_value"]')将选择任何数据属性精确值为the_exact_value的元素,例如:

<div data-test="the_exact_value">Exact Matches</div>

但不是

<div data-test="the_exact_value foo">This won't match</div>

其他回答

$('*[data-customerID="22"]');

您应该可以省略*,但如果我没记错的话,这可能会给出错误的结果,这取决于您使用的jQuery版本。

注意,为了与selector API (document.querySelector{,all})兼容,在这种情况下不能省略属性值(22)周围的引号。

另外,如果你经常在jQuery脚本中使用数据属性,你可能会考虑使用HTML5自定义数据属性插件。这允许您通过使用. dataattr ('foo')编写更可读的代码,并导致缩小后的文件大小更小(与使用.attr('data-foo')相比)。

我还没见过没有jQuery的JavaScript答案。希望它能帮助到某些人。

var elements = document.querySelectorAll('[data-customerID="22"]'); 元素[0]。innerHTML = '它工作了!'; 测试< data-customerID = ' 22 ' > < / >

信息:

数据属性 .querySelectorAll ();

只是用“生活标准”的一些特征来完成所有的答案-到目前为止(在html5时代),没有第三方libs是可能做到的:

纯/纯JS与querySelector(使用css选择器): select document.querySelector('[data-answer="42"],[type="submit"]') select所有DOM: document.querySelectorAll('[data-answer="42"],[type="submit"]') 纯/纯CSS 一些特定的标签:[data-answer="42"],[type="submit"] 所有具有特定属性的标签:[data-answer]或input[type]

它会工作的:)

$('.ic-star[data-rate=“1”]').addClass('rated');

通过Jquery filter()方法:

http://jsfiddle.net/9n4e1agn/1/

HTML:

<button   data-id='1'>One</button>
<button   data-id='2'>Two</button>

JavaScript:

$(function() {    
    $('button').filter(function(){
        return $(this).data("id")   == 2}).css({background:'red'});  
     });