Jquery 如何选择html的两级层次结构?
假设,这个htmlJquery 如何选择html的两级层次结构?,jquery,Jquery,假设,这个html <div id="main"> <div><!--should select this--> <article>should not select this</article> </div> <div><!--should not select this--> <article>should select this</article&g
<div id="main">
<div><!--should select this-->
<article>should not select this</article>
</div>
<div><!--should not select this-->
<article>should select this</article>
<article>should select this</article>
</div>
</div>
不应选择此选项
你应该选择这个
你应该选择这个
要重新声明我的问题:我想选择文章的一级父级,如果文章只有一个,并且如果文章不止一个,则不应选择它的一级父级,而应选择文章本身
我需要更干净的方法来选择这个作为选择器
$('article').filter(function () {
return $(this).siblings().length===0 ? true : false;
});
// Or in each-syntax:
$('article').each(function(){
var $siblings = $(this).siblings(); // select (possible) siblings
if( $siblings .length ===0 ){ // of none found
$elem = $(this).parent(); // select parent
}
else{
$elem = $siblings; // otherwise get the siblings
}
});
本例使用了一个或多个过滤器,但您可以用.map()
函数替换它,我这样做是为了演示它是如何工作的
对于那些我们关心的人:我已经测试了兄弟姐妹的结果,如果你有3篇文章,测试其中1篇他们有多少兄弟姐妹,上面说2篇。它排斥自己
编辑:误解,更新答案,请查看否决票:)尝试
var $els = $('#main').find('> div, > div > article').filter(function () {
return this.tagName == 'DIV' ? $(this).children().length == 1 : $(this).siblings().length > 0
});
console.log($els.get())
演示:在第二种情况下,应该选择哪篇文章?文章本身还是它的兄弟?不应该选择我的示例中的文章和文章div中的文章本身。