如何通过jQuery中的自定义属性的特定值获取元素? [英] How to get elements by a specific value of a custom attribute in jQuery?

查看:3034
本文介绍了如何通过jQuery中的自定义属性的特定值获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 data-role 的自定义属性,我想在jQuery中找到 data-role ="content" 的所有元素.

I have a custom attribute called data-role and I'd like to find all elements where data-role="content" in jQuery.

我目前正在使用一些旧的JavaScript代码进行此操作:

I'm currently doing this with some old JavaScript code:

var elements = element.getElementsByTagName(tagName);
for(var i=0; i<elements.length; i++) {
  if(elements[i].getAttribute("data-role") == "content") {
    // does something evil
  }
}

免责声明:未检查代码,只是将其快速写下来.

Disclaimer: Code was not checked, just wrote it down quickly.

我感觉到jQuery中有一个优雅的1行解决方案,但是我是一个新手.我无法入睡,所以我也许不知道,所以也许您stackoverflowers可以帮助兄弟. ;-)

I've got a feeling that there's an elegant 1-line solution in jQuery, but I'm a novice. And I can't sleep before I know, so perhaps you stackoverflowers can help a bro out. ;-)

推荐答案

$("tagName[attribute='value']")

或者,就您而言:

$("div[data-role='content']")

将返回正确的元素.

从那里开始,如果要遍历与该选择器和do something evil相匹配的元素集,则可以:

From there, if you wanted to iterate over the set of elements that match this selector and do something evil, you could:

$("[data-role='content']").each(function(index){

     Do something evil
     $(this) is the current element in the iteration
});

请注意,tagName是可选的. jQuery选择器可以随意连接,因此您可以同时查询标记名(简单字符串),id(以#开头),类(以.开头)或属性(如上方括号所示)或任何其他内容它们的有限组合,例如:

Please note that the tagName is optional. JQuery selectors can be concatenated at will, so you can query simulataneously for tagname (simple string), id (prefaced by #), class (prefaced by .) or attribute (in square brackets as above), or for any limited combination of them eg:

 $("tagName#someId.someClass.someOtherClass[attribute='value']")
 $("[attribute='value']")
 $('tagName')
 $('#someId')

是所有有效查询,但是请记住,jquery将仅返回与查询中所有条件匹配的元素.

Are all valid queries, however keep in mind that jquery will only return elements that match ALL conditions in the query.

这篇关于如何通过jQuery中的自定义属性的特定值获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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