【问题标题】:Get parent <li> item with jQuery使用 jQuery 获取父 <li> 项
【发布时间】:2012-05-13 18:49:13
【问题描述】:

当我单击特定的 &lt;li&gt; 项目时,我试图获取父级 &lt;li&gt;

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

假设我点击了submodule 1,我得到了带有$(this).attr('id'); 的点击ID 我现在如何获取父 &lt;li&gt; 的 ID,在本例中为 module 1

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

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

【问题讨论】:

  • 这是一个基于Java的应用程序,我正在使用JSP构建网站!
  • @dooonot - 但是这个问题与 Java 没有任何关系,因此这个问题和随后删除了“Java”标签。

标签: javascript jquery html jquery-selectors treeview


【解决方案1】:
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】:
    var parent = $(this).closest("li");
    

    【讨论】:

    • 我无法让它工作。它总是说undefined。请查看我更新的jsfiddle
    【解决方案3】:

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

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

    来自 jQuery 文档:

    获取第一个匹配选择器的元素,从 当前元素并在 DOM 树中向上移动。

    【讨论】:

    • 如果点击处理程序绑定到最低 li 的跨度,它只会得到它的父 li。或者如果绑定到最低 li,它会自己获取
    • 这项工作需要吗? var id = $(this).closest("li").attr('id');
    • @dooonot - 是的,假设最近的 li 元素有一个 id
    • 我只看到存储id的不是li元素,而是被li元素包围的span元素。我该怎么做才能得到这个id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多