使用jQuery在并行树路径中查找html元素

时间:2015-12-28 16:44:54

标签: javascript jquery html

我们说我有这段HT​​ML:

<div>
   <a class="target"/>
   <div>
        <a class="target"/>
        <div>
            <hr class="source"/>
        </div>
   </div>
</div>

我想从源头找到最接近的目标,这意味着我需要攀爬最少量的父母。通过绑定,我得到了源元素,我会注意到源代码。我想找到第二个锚,这是两个级别的深度,因为它更靠近我的源hr。

我现在所拥有的是什么,有效:

var target = source
   .parentsUntil(".target").eq(0)
   .find(".target")[0];
但是,这似乎相当无效,因为父母将会测试并返回太多的父母。我希望它停止在包含.target元素的第一个父级上。然后我觉得在使用jQuery查找目标之后再调用find,而它之前已经找到了parentUntil。

我可以想到另一种解决方案,它涉及迭代source.parents()并调用find直到我得到一个结果,但仍然会搜索已经探索过的分支。

是否有jQuery中的函数或自定义算法,我可以通过仅探索需要探索的树的部分来获取我的结果?

2 个答案:

答案 0 :(得分:3)

我建议:

// starts at the element(s) with the class of
// 'source':
$('.source')
  // finds the closest <div> element that contains
  // an <a> element with the class-name of 'target':
  .closest('div:has("a.target")')
  // finds that contained <a> element with
  // the class of 'target':
  .find('a.target');

&#13;
&#13;
$('.source').closest('div:has("a.target")').find('a.target').addClass('found');
&#13;
a::before {
  content: attr(class);
}
.found {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a class="target"></a>
  <div>
    <a class="target"></a>
    <div>
      <hr class="source" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:0)

在您的情况下,您可以使用.parent()选择.source元素的父div,并使用.prev()获取您案例中<a>的前一个元素

$('.source').parent().prev()

或者您可以使用

$('.source').parent().parent().find('a.target')
相关问题