我试图在点击特定的<li>
项时获取父级<li>
。
http://jsfiddle.net/doonot/GjbZk/
假设我点击了“submodule 1”,我可以使用“$(this).attr('id')”获取到所点击的ID。那么现在我该如何获取这个父级请注意,我的树很大,因此必须具有灵活性。
谢谢你,非常感谢你的回答。
我试图在点击特定的<li>
项时获取父级<li>
。
http://jsfiddle.net/doonot/GjbZk/
假设我点击了“submodule 1”,我可以使用“$(this).attr('id')”获取到所点击的ID。那么现在我该如何获取这个父级closest
方法获取第一个匹配选择器的祖先元素:var li = $(this).closest("li");
根据jQuery文档:
获取与选择器匹配的第一个元素,从当前元素开始通过DOM树向上进行。
var id = $(this).closest("li").attr('id');
- nimrodli
元素有一个id
。 - James Allardiceid
的不是li
元素,而是被li
元素包围的span
元素。我该怎么做才能获取这个id
? - nimrodvar 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
var parent = $(this).closest("li");