使用jQuery获取父<li>项

nim*_*rod 6 javascript treeview jquery html5 jquery-selectors

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

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

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

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

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

Jam*_*ice 22

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

var li = $(this).closest("li");
Run Code Online (Sandbox Code Playgroud)

来自jQuery文档:

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


Jos*_*eph 9

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
Run Code Online (Sandbox Code Playgroud)


zvo*_*ona 5

var parent = $(this).closest("li");
Run Code Online (Sandbox Code Playgroud)