使用jQuery通过数据属性选择元素 [英] Selecting element by data attribute with jQuery
问题描述
是否有一种简单而直接的方法来根据其data
属性选择元素?例如,选择所有具有名为customerID
的数据属性且值为22
的锚.
Is there an easy and straight-forward method to select elements based on their data
attribute? For example, select all anchors that has data attribute named customerID
which has value of 22
.
我有点不愿意使用rel
或其他属性来存储此类信息,但是我发现根据存储在其中的数据来选择元素要困难得多.
I am kind of hesitant to use rel
or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.
推荐答案
$('*[data-customerID="22"]');
您应该可以省略*
,但是如果我没记错的话,根据您使用的jQuery版本,这可能会导致错误的结果.
You should be able to omit the *
, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.
请注意,为了与Selectors API(document.querySelector{,all}
)兼容,属性值(22
)周围的引号.
Note that for compatibility with the Selectors API (document.querySelector{,all}
), the quotes around the attribute value (22
) may not be omitted in this case.
此外,如果您在jQuery脚本中大量使用数据属性,则可能要考虑使用
Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo')
, and results in a smaller file size after minification (compared to using .attr('data-foo')
).
这篇关于使用jQuery通过数据属性选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!