本文介绍了类似于最接近的 jQuery 函数,它将返回父链之外的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何 jQuery 函数类似于最接近()会返回父链之外的元素,横向遍历?例如,我想在 div 源上调用一个函数 foo() 来返回 div 目标.我知道我可以使用 parent() 和兄弟姐妹 () 进行导航,但我需要一些通用的东西,可以根据需要向上、横向和向下移动多个级别?

var allsources = $('.source');allsources.click(function()){$(this).closest('.target').hide();});<div class="row"><div><div class="target" ></div>

<div><div><div class="source"></div>

<div class="row"><div><div class="target" ></div>

<div><div><div class="source"></div>

我对最接近的定义:你有一个元素源.试着找到它.如果找到多个,则返回一个节点数较少的节点/下一个/上一个.如果未找到,请上一级,然后再次尝试查找.重复直到没有父母.

解决方案

如果,最接近的意思是尽可能少往上走,然后往下走",那么你可以这样做

$("#source").closest(":has(.target)").find(".target:first")//确保在平局的情况下我们只选择一个元素

在您的情况下,最好直接指定公共父级:

$(this).closest(".row").find(".target")//这里没有平局,不需要仲裁

Is there any jQuery function similar to closest() that will return elements outside of the parent chain, traversing sideways? For example, I want to call a function foo() on the div source that would return the div target. I know I could navigate using parent() and siblings(), but I need something generic that would go as many levels as needed, up, sideways and down?

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>

EDIT:

My definition of closest: you have an element source. Try to find it down. If find more than one, return one that is less node hoops down/next/prev. If not found, go one level up, and try to find again. Repeat until no parent.

解决方案

If, by closest, you mean "travel up as little as possible, then anywhere downwards", then you can do

$("#source")
  .closest(":has(.target)")
  .find(".target:first")  //make sure we only select one element in case of a tie

In your case, it would be better to specify the common parent directly:

$(this)
  .closest(".row")
  .find(".target")        //there's no tie here, no need to arbitrate

这篇关于类似于最接近的 jQuery 函数,它将返回父链之外的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 06:09