查找与上下文相关(而不仅仅是包含在上下文中)的最接近的父级
使用以下 html,
<ul id="accordion">
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
</ul>
我将外部 ul 存储在变量中
var acc = $("#accordion")[0]
在一般情况下,我只是传递了 DOM 元素,不一定指定选择器
当单击 h3 时,我想获取顶部包含它的级别 li。 在一般情况下,手风琴 ul 和我想要获取的元素之间以及要获取的元素和 h3 之间可能存在任何类型的标记...但我将拥有一个选择器这让我可以使用“>”从手风琴中获取元素选择器。
例如 var items = $(">li", acc);
问题是,当我从单击的 h3(单击处理程序中的“this”)开始时,很难找到特定的项目。
$(this).closest(">li", acc);
返回一个空的 jQuery(也许是一个错误?尽管在这种情况下很难定义“>”的含义,其中顶级元素是动态的)
$(this).parents(">li")
设置上下文,因此可能会返回太多元素
不允许 有办法做我想做的事吗?
*编辑:html 现在使问题更加清晰
With the following html
<ul id="accordion">
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
<li>
<ul>
<li><h3>title</h3></li>
</ul>
</li>
</ul>
I have the outer ul stored in a variable
var acc = $("#accordion")[0]
in the general case I am just passed the DOM element and can't necessarily specify a selector
When a h3 is clicked I want to get the top level li that contains it. In the general case there could be any kind of markup between the accordion ul and the element I wnat to fetch, and between the element to fetch and the h3... but what I will have is a selector that lets me get to the element from the accordion using the ">" selector.
e.g. var items = $(">li", acc);
The trouble is that when I start from a clicked h3 ("this" inside the click handler) It's difficult to find the specific item.
$(this).closest(">li", acc);
returns an empty jQuery (maybe a bug? although it's difficult to define what ">" means in this instance, where the top level element is dynamic)
$(this).parents(">li")
doesn't allow a context to be set, so could potentially return too many elements
Is there a way to do what I want?
*edit: html now makes the problem clearer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$(h3).closest(".item");
怎么样?根据“closest”文档,它将从当前节点向上遍历 DOM,直到找到与您的选择器匹配的节点。How about
$(h3).closest(".item");
? According to "closest" documentation, it will traverse the DOM up from current node until it finds a node that matches your selector.反之,保证子关系:
Go the other way, to guarantee the child relationship:
工作一般;在初始 jQuery 上设置上下文似乎是唯一用“>”开始选择器的地方在 jQuery 中工作
works in general; setting a context on an initial jQuery appears to be the only place that startinga selector with ">" works in jQuery