Shp*_*ord 91 javascript jquery jquery-selectors custom-data-attribute
我正在尝试选择具有data-go-to非空属性的所有元素.
我试过$('[data-go-to!=""]')但奇怪的是,如果我这样做的话,它似乎正在选择页面上的每一个元素.
gmo*_*gmo 172
正如进一步的参考,和最新的 (may'14) (aug'15) (sep'16) (apr'17)(mar'18) ...
答案适用于:
空字符串:
如果必须存在并且可以有任何价值(或根本没有)
attr
jQuery("[href]");
Run Code Online (Sandbox Code Playgroud)
缺少属性:
如果可能存在且存在,则必须具有一定价值
attr
jQuery("[href!='']");
Run Code Online (Sandbox Code Playgroud)
或两者:
如果必须存在并且必须具有一定的价值......
attr
jQuery("[href!=''][href]");
Run Code Online (Sandbox Code Playgroud)
PS:可能有更多组合......
jQuery v1.11.0 -> jsFiddle online testjQuery v2.1.0 -> jsFiddle online testjQuery v2.1.3 -> jsFiddle online testjQuery v3.0.0-alpha1 -> jsFiddle online testjQuery v3.1.1 Slim -> jsFiddle online test jQuery v3.2.1 -> jsFiddle online test jQuery v3.3.1 -> jsFiddle online test 最后的jQuery版本于5月29日在jsFiddle中提供 jQuery Edge -> jsFiddle online test jQuery边缘版(谨慎使用) *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');Run Code Online (Sandbox Code Playgroud)
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%;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
Ben*_*man 75
尝试
$(':not([data-go-to=""])')
Run Code Online (Sandbox Code Playgroud)
更新:
为了不让任何人误入歧途,这个答案将适用于旧版本的jQuery,但不具备面向未来的能力.由于@gmo和@ siva的答案似乎都适用于以后的版本,我会推迟(并鼓励你赞成)他们的答案....当然希望你有一个美好的一天.
Siv*_*ran 19
$('[data-go-to!=""]:[data-go-to]').each(function() {
// Do Your Stuff
});?
Run Code Online (Sandbox Code Playgroud)
我不确定一个简单的选择器,但你可以使用filter():
$('[data-go-to]').filter(
function(){
return ($(this).attr('data-go-to').length > 0);
});
Run Code Online (Sandbox Code Playgroud)
参考文献:
具有“ data-attributename”,其值不为空:
$('[data-attributename]:not([data-attributename=""])')
Run Code Online (Sandbox Code Playgroud)
'data-attributename'是否为空:
$('[data-attributename]')
Run Code Online (Sandbox Code Playgroud)