gpt4 book ai didi

javascript - jquery 找到 child 而不是孙子

转载 作者:行者123 更新时间:2023-11-30 08:23:30 24 4
gpt4 key购买 nike

我想使用 jQuery 选择器选择所有子 div 并忽略孙子 div,我以这个为例:

$('.main').find('.this').show(); // shows the first only
div.this{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main'>
<div>
... a lot of more divs levels ...
<div>
<div class='this'>show this!!!!!!!!!!
<div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
</div>
</div>
<div class='this'>show this!!!!!!!!!!
<div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

我想在找到的第一个级别上选择“this”元素,但不进行更深入的搜索,因此以下代码均无效:

$('.main').find('.this').show(); // shows them all
$('.main').find('.this').show(); // select both
$('.main').find('.this').eq(0).show(); // shows the first only
$('.main').find('.this').first().show(); // shows the first only
$('.main .this:nth-child(1)').show(); // shows the first only and his childs
$('.main').find('.this').siblings().show(); // doesn't show anything
$('.main > div > div > .this').show(); // we don't know how deep level is
$('.main').children('.this').show(); // we don't know how deep level is
$('.main').closest('.this').show(); // looks up through its ancestors only

测试所有答案

// Kevin B
$('.main').find('.this').first().siblings('.this').addBack().show() // it works, I don't know how!
// Alexander Solonik
$('.main').find('.this').eq(0).siblings('.this').addBack().show() // this one also works, why!?

可以限制我要查找的级别数吗?

最佳答案

如果您尝试查找第一级元素,但这些元素不是直接后代,则可以结合使用 find()eq() , siblings(), 和 addBack() 获取第一级元素。

$('.main').find('.this').eq(0).siblings('.this').addBack().show()
div.this {
height: 20px;
background: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main'>
<div>
... a lot of more divs levels ...
<div>
<div class='this'>show this!!!!!!!!!!
<div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
</div>
</div>
<div class='this'>show this!!!!!!!!!!
<div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
<div>
<div class='this'>do not show this
<div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

关于javascript - jquery 找到 child 而不是孙子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com