类似于最接近的jQuery函数将返回父链之外的元素

tie*_*tie 3 javascript jquery

是否有任何类似于nearest()的jQuery函数将返回父链外部的元素,横向移动?例如,我想在div源上调用一个函数foo()来返回div目标.我知道我可以使用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>
Run Code Online (Sandbox Code Playgroud)

编辑:

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

Joh*_*rak 5

如果,通过最接近,你的意思是"尽可能少地向上旅行,然后在任何地方向下",那么你就可以做到

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

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

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