使用jQuery </li>获取父<li>项

时间:2012-05-04 08:19:50

标签: javascript jquery html5 jquery-selectors treeview

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

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

所以,我要点击submodule 1,点击$(this).attr('id');点击的ID 我现在如何获取父<li>的ID module 1

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

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

3 个答案:

答案 0 :(得分:21)

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

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

来自jQuery文档:

  

获取与选择器匹配的第一个元素,从   当前元素并在DOM树中前进。

答案 1 :(得分: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

答案 2 :(得分:3)

var parent = $(this).closest("li");
相关问题