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

查看:24
本文介绍了使用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 脚本中大量使用数据属性,您可能需要考虑使用 HTML5 自定义数据属性插件.这允许您使用 .dataAttr('foo') 编写更具可读性的代码,并在缩小后产生更小的文件大小(与使用 .attr('data-foo')).

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天全站免登陆