Javascript 使用 jQuery 获取父 <li> 项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10445205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:20:26  来源:igfitidea点击:

Get parent <li> item with jQuery

javascriptjqueryhtmljquery-selectorstreeview

提问by nimrod

I am trying to get the parent <li>when I click on a specific <li>item.

<li>当我单击特定<li>项目时,我正在尝试获取父项。

http://jsfiddle.net/doonot/GjbZk/

http://jsfiddle.net/doonot/GjbZk/

So let's say I click on submodule 1, I get the clicked ID with $(this).attr('id');How can I now get the ID of the parent <li>which is in this case module 1?

所以假设我点击了submodule 1,我得到了点击的 ID,在这种情况下,$(this).attr('id');我现在如何获得父级的 ID ?<li>module 1

Please note that my tree is quite big, so it has to be flexible.

请注意,我的树很大,所以它必须是灵活的。

Thanks a lot, much appreciate your answer.

非常感谢,非常感谢您的回答。

回答by James Allardice

You can use the closestmethod to get the first ancestor that matches a selector:

您可以使用该closest方法获取与选择器匹配的第一个祖先:

var li = $(this).closest("li");

From the jQuery docs:

来自 jQuery 文档:

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

获取与选择器匹配的第一个元素,从当前元素开始并向上遍历 DOM 树。

回答by Joseph

var parentModule = $('this')             //the selector of your span
    .parents('li:eq(1)')                 //get the next li parent, not the direct li
    .children('.rightclickarea:first')   //get the first element, which would be the span
    .attr('id')                          //get the span id

回答by Samuli Hakoniemi

var parent = $(this).closest("li");