如何在jQuery中我只选择div元素中的链接而不是该div中包含的子div元素?
<div>
<a>Link 1</a>
<a>Link 2</a>
<div>
<a>Not these 1</a>
<a>Not these 2</a>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
red*_*are 11
使用直接子选择器>
例如
$('div>a')
Run Code Online (Sandbox Code Playgroud)
更新: 安抚RoBorg先生
如果你在第一个div内的嵌套元素中有锚点,则以下内容将起作用.这使用过滤器来确保父div确实是您要定位的div而不是嵌套的div.
var firstDivAnchors = $('div a').filter( function(){
return $(this).closest('div').is('#yourDiv');
});
Run Code Online (Sandbox Code Playgroud)