是否有任何类似于 closest() 的 jQuery 函数会返回父链之外的元素,横向遍历?例如,我想在将返回 div 目标的 div 源上调用函数 foo()。我知道我可以使用 parent() 和 siblings() 进行导航,但我需要一些通用的东西,可以根据需要向上、横向和向下移动多个级别?
var allsources = $('.source');
allsources.click(function()){
$(this).closest('.target').hide();
});
<div class="row">
<div>
<div class="target" ></div>
</div>
<div>
<div>
<div class="source"></div>
</div>
</div>
</div>
<div class="row">
<div>
<div class="target" ></div>
</div>
<div>
<div>
<div class="source"></div>
</div>
</div>
</div>
编辑:
我对最接近的定义:你有一个元素源。试着找到它。如果找到多个,则返回一个小于节点环的向下/下一个/上一个。如果找不到,请上一层,然后再次尝试查找。重复直到没有 parent 。
最佳答案
如果通过最近,您的意思是“尽可能少地向上移动,然后向下移动”,那么您可以这样做
$("#source")
.closest(":has(.target)")
.find(".target:first") //make sure we only select one element in case of a tie
在您的情况下,最好直接指定公共(public)父级:
$(this)
.closest(".row")
.find(".target") //there's no tie here, no need to arbitrate
关于javascript - 类似于 closest 的 jQuery 函数将返回父链之外的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13641938/