gpt4 book ai didi

javascript - jquery dom中某处最近的元素(模糊搜索)

转载 作者:可可西里 更新时间:2023-11-01 13:14:15 27 4
gpt4 key购买 nike

是否有内置的 jQuery 方法可以找到离另一个元素最近的 dom 元素?我的意思是最近 - 从一个到另一个的相对路径(例如 XPath)的最小长度最近。

考虑以下示例(来自 Twitter Bootstrap 的下拉框)。有下拉图标 - 带有 .JS-ACTIONS 的元素和一组链接 - 带有 .JS-DELETE 的元素,当其中一个链接点击进度条时- 应该启用向下图标。

<div class='btn-group'>
<a href='#' class='btn dropdown-toggle JS-ACTIONS' data-toggle='dropdown'>
<i class='icon-cog'></i>
<span class="caret"></span>
</a>
<ul class='dropdown-menu pull-right'>
<li><a href='#' class='JS-DELETE'>Delete</a></li>
</ul>
</div>

一种方法,使用类似的东西

$(element.currentTarget).parent().parent().find('.JS-ACTIONS').showProgress()

但我希望 JavaScript 独立于 DOM 结构,比如

$(element.currentTarget).nearest('.JS-ACTIONS').showProgress()

jQuery中有这样的方法吗?

更新

jQuery 的closest 方法不起作用,它只在 parent 中搜索,它不在 sibling 和 parent 的其他 child 中搜索。

最佳答案

您可能需要 closest() :

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$(element.currentTarget).closest('.JS-ACTIONS').showProgress()

关于javascript - jquery dom中某处最近的元素(模糊搜索),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13570537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com