使用 jQuery 按数据属性选择元素
是否有一种简单直接的方法来根据元素的 data
属性来选择元素?例如,选择具有名为 customerID
的数据属性(其值为 22
)的所有锚点。
我有点犹豫是否使用 rel 或其他属性来存储此类信息,但我发现根据存储在其中的数据来选择元素要困难得多。
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
.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
您应该能够省略
*
,但如果我没记错的话,根据您使用的 jQuery 版本,这可能会产生错误的结果。请注意,为了与 Selectors API (
document.querySelector{,all}
) 兼容,属性值周围的引号 (22
) 在这种情况下不能省略。另外,如果您在 jQuery 脚本中经常使用数据属性,您可能需要考虑使用 HTML5 自定义数据属性插件。这允许您使用
.dataAttr('foo')
编写更具可读性的代码,并在缩小后产生更小的文件大小(与使用.attr('data-foo' 相比) )
)。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.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.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')
).对于通过谷歌搜索并想要使用数据属性进行选择的更通用规则的人:
$("[data-test]")
将选择仅具有数据属性的任何元素(无论属性的值如何)。包括:$('[data-test~="foo"]')
将选择数据属性包含但不包含foo
的任何元素不必精确,例如:$('[data-test="the_exact_value"]')
将选择数据属性精确值为the_exact_value
的任何元素,例如:但不是
For people Googling and want more general rules about selecting with data-attributes:
$("[data-test]")
will select any element that merely has the data attribute (no matter the value of the attribute). Including:$('[data-test~="foo"]')
will select any element where the data attribute containsfoo
but doesn't have to be exact, such as:$('[data-test="the_exact_value"]')
will select any element where the data attribute exact value isthe_exact_value
, for example:but not
使用
$('[data-whatever="myvalue"]')
将选择具有 html 属性的任何内容,但在较新的 jQueries 中,似乎如果您使用$(...).data (...)
附加数据,它使用一些神奇的浏览器东西并且不会影响 html,因此不会被.find
发现,如 上一个答案。验证(使用 1.7.2+ 进行测试)(另请参阅 fiddle):(更新为更完整)
Using
$('[data-whatever="myvalue"]')
will select anything with html attributes, but in newer jQueries it seems that if you use$(...).data(...)
to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by.find
as indicated in the previous answer.Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)
我还没有看到没有 jQuery 的 JavaScript 答案。希望它能帮助某人。
信息:
数据属性
.querySelectorAll();
I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.
Info:
data attributes
.querySelectorAll();
要选择具有数据属性
data-customerID==22
的所有锚点,您应该包含a
以将搜索范围限制为仅该元素类型。当页面上有很多元素时,以大循环或高频率执行数据属性搜索可能会导致性能问题。To select all anchors with the data attribute
data-customerID==22
, you should include thea
to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.原生 JS 示例
获取元素的 NodeList
html:
获取第一个元素
html:
定位返回节点列表的节点集合
html:
获取基于以下内容的元素多个(OR)数据值
html:
根据组合(AND)数据值获取元素
html:
获取值开头的项目
Native JS Examples
Get NodeList of elements
html:
<div data-id="container"></div>
Get the first element
html:
<div id="container"></div>
Target a collection of nodes which returns a nodelist
html:
Get elements based on multiple (OR) data values
html:
Get elements based on combined (AND) data values
html:
Get items where the value starts with
通过 Jquery filter() 方法:
http://jsfiddle.net/9n4e1agn/1/
HTML:
JavaScript:
via Jquery filter() method:
http://jsfiddle.net/9n4e1agn/1/
HTML:
JavaScript:
像这样的结构:
$('[data-XXX=111]')
在 Safari 8.0 中不起作用。如果您这样设置数据属性:
$('div').data('XXX', 111)
,则只有直接在 DOM 中设置数据属性才有效:$( 'div').attr('data-XXX', 111)
.我认为这是因为 jQuery 团队优化了垃圾收集器,以防止内存泄漏和每个更改数据属性上的 DOM 重建的繁重操作。
The construction like this:
$('[data-XXX=111]')
isn't working in Safari 8.0.If you set data attribute this way:
$('div').data('XXX', 111)
, it only works if you set data attribute directly in DOM like this:$('div').attr('data-XXX', 111)
.I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.
要使其在 Chrome 中发挥作用,该值必须不能有另一对引号。
它只能工作,例如,像这样:
For this to work in Chrome the value must not have another pair of quotes.
It only works, for example, like this:
有时需要根据元素是否以编程方式附加数据项来过滤元素(也称为不通过 dom 属性):
上面的方法可以工作,但可读性不是很好。更好的方法是使用伪选择器来测试此类事情:
现在我们可以将原始语句重构为更流畅和可读的内容:
It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):
The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:
Now we can refactor the original statement to something more fluent and readable:
只是为了用“生活标准”的一些功能来完成所有答案 - 到目前为止(在 html5 时代)无需第三方库就可以做到这一点:
document.querySelector('[data-answer="42"],[type="submit"]')
document.querySelectorAll('[data-answer="42"],[type="submit"]')
[data-answer="42"],[type="submit"]
[data-answer]
或input[type]
Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:
document.querySelector('[data-answer="42"],[type="submit"]')
document.querySelectorAll('[data-answer="42"],[type="submit"]')
[data-answer="42"],[type="submit"]
[data-answer]
orinput[type]
它会起作用:)
$('.ic-star[data-rate="1"]').addClass('erated');
It will work :)
$('.ic-star[data-rate="1"]').addClass('rated');