Javascript 查找具有特定数据属性的元素 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11747750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:57:52  来源:igfitidea点击:

Find an element with a specific data attribute jQuery

javascriptjqueryhtml

提问by user974896

I understand that I can always iterate down the DOM tree and check every element for a data field and if the value is correct but I would like a cleaner solution. For example

我知道我总是可以遍历 DOM 树并检查数据字段的每个元素以及值是否正确,但我想要一个更清晰的解决方案。例如

    <div id="theDiv">
       <div>
         <span data-num="3" ></span>
         OTHER HTML
       </div>
       <div>
         <div><span data-num="23"></span><div>
         OTHER HTML
       </div>
       <div>
         <span data-num="3"></span>
         OTHER HTML
       </div>
    </div>

Is there a jQuery one liner to find all spans with data-num=3? I know I can find all spans by

是否有 jQuery one liner 可以找到 data-num=3 的所有跨度?我知道我可以找到所有跨度

  $("#theDiv").find(span).each(function(e) { ... });

but I would like something like

但我想要类似的东西

  $("#theDiv").find(span > data-num=3).each(function(e) { ... });

回答by Adam

Use the Attribute Equals Selector

使用属性等于选择器

 $("#theDiv span[data-num='3']")

Try it!

尝试一下!

回答by voodoo417

only for example ( filter)

仅举例(过滤器)

$('#theDiv span').filter(function(){ return $(this).data("num") == 3});