使用jQuery获取父级<li>元素

9

我试图在点击特定的<li>项时获取父级<li>

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

假设我点击了“submodule 1”,我可以使用“$(this).attr('id')”获取到所点击的ID。那么现在我该如何获取这个父级
  • 的ID呢?在这种情况下,它是“module 1”。
    请注意,我的树很大,因此必须具有灵活性。
    谢谢你,非常感谢你的回答。

  • 这是一个基于Java的应用程序,我正在使用JSP构建网站! - nimrod
    1
    @dooonot - 但这个问题与Java无关,因此问题和随后的“Java”标签已被删除。 - James Allardice
    3个回答

    28
    你可以使用 closest 方法获取第一个匹配选择器的祖先元素:
    var li = $(this).closest("li");
    

    根据jQuery文档:

    获取与选择器匹配的第一个元素,从当前元素开始通过DOM树向上进行。


    如果点击处理程序绑定到最低的li中的span,则它只会获取其父li。或者如果绑定到最低的li,则它将获取自己。 - Joseph
    1
    这段代码是否有效?var id = $(this).closest("li").attr('id'); - nimrod
    @dooonot - 是的,假设最近的li元素有一个id - James Allardice
    我刚才看到存储id的不是li元素,而是被li元素包围的span元素。我该怎么做才能获取这个id - nimrod

    10
    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
    

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

    1
    我无法使其运作。它总是显示“未定义”。请参阅我的更新的jsfiddle - nimrod

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接