jQuery:选择不为空的数据属性?

新手上路,请多包涵

我正在尝试选择所有具有非空属性 data-go-to 的元素。

我已经尝试过 $('[data-go-to!=""]') 但奇怪的是,如果我这样做,它似乎会选择页面上的每个元素。

原文由 Shpigford 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 285
2 个回答

尝试

$(':not([data-go-to=""])')

更新:

为了不让任何人误入歧途,这个答案将适用于旧版本的 jQuery 但不是面向未来的。由于@gmo 和@siva 的回答似乎都适用于更高版本,因此我尊重(并鼓励您投票)他们的回答……当然希望您有美好的一天。

原文由 Benjamin Oman 发布,翻译遵循 CC BY-SA 3.0 许可协议

作为进一步的参考,以及 _最新的_(may’14)(aug’15)(sep’16)(apr’17)(mar’18)(mar’19)(may’20) ( jan’ 22 )

适用的答案:

###Empty 字符串:如果 attr 必须 存在并且 可以 有任何值 (或根本没有)

     jQuery("[href]");

###Missing attributes: If attr 可能 存在 & 如果存在, 必须 有一些值

    jQuery("[href!='']");

###Or both: If attr 必须 存在 并且必须有 一些价值……

     jQuery("[href!=''][href]");


PS :更多组合是可能的……


###在 jsFiddle 中检查此测试以获取示例:


###Or here in SO with this Code Snippet

\* 片段正在运行 jQuery v2.1.1

 jQuery('div.test_1 > a[href]').addClass('match');
jQuery('div.test_2 > a[href!=""]').addClass('match');
jQuery('div.test_3 > a[href!=""][href]').addClass('match');
 div,a {
    display: block;
    color: #333;
    margin: 5px;
    padding: 5px;
    border: 1px solid #333;
}
h4 {
    margin: 0;
}
a {
    width: 200px;
    background: #ccc;
    border-radius: 2px;
    text-decoration: none;
}
a.match {
    background-color: #16BB2A;
    position: relative;
}
a.match:after {
    content: 'Match!';
    position: absolute;
    left: 105%;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_1">
    <h4>Test 1: jQuery('a[href]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>
<div class="test_2">
    <h4>Test 2: jQuery('a[href!=""]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>
<div class="test_3">
    <h4>Test 3: jQuery('a[href!=""][href]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>

原文由 gmo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏