使用jQuery通过数据属性选择元素 [英] Selecting element by data attribute with jQuery

查看:96
本文介绍了使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆