javascript - 类似于 closest 的 jQuery 函数将返回父链之外的元素

标签 javascript jquery

是否有任何类似于 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/

相关文章:

javascript - SubscriptionConfirmation 请求中的 Token 或 SubscribeUrl 在哪里?

javascript - 从包含中文和拉丁字符的电子邮件字段中检索原始值

javascript - JQuery 表排序器 : Have column show as another is sorted

javascript - 正则表达式 javascript/jquery 与 url

javascript - 单击超链接打开的 jquery 模式立即消失

javascript - 简单的谷歌浏览器扩展来检测网页上的点击 - 没有显示警报(错误)

javascript - 如何搜索所有级别嵌套的 Javascript 对象

javascript - 在javascript中将用户位置与谷歌地图同步

javascript - 通过 src 值查找 img 标签并在 img 标签中添加新属性

javascript - 无法在 superslides jquery 插件上加载 ajax 内容