Javascript 单击时获取父元素的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27842138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID of parent element on click
提问by Omkar
I'm trying to display ID of parent ULon LIclick. but the alert is displaying value as undefined. Where am I going wrong?
我正在尝试UL在LI单击时显示父级的 ID 。但警报显示值未定义。我哪里错了?
HTML:
HTML:
<ul id='uiID'>
<li id='myLi'>A</li>
</ul>
JavaScript
JavaScript
var x = document.getElementById("myLI").parentNode.nodeName;
alert(x.id);
回答by Amit Joki
You're not attaching any click event to the element and nodeNamein your case returns LI, so that's not wanted. What you want is
您没有将任何点击事件附加到元素,nodeName在您的情况下返回LI,所以这是不想要的。你想要的是
document.getElementById("myLI").onclick = function(e){
alert(e.target.parentNode.id);
}
回答by potashin
You can do something like this :
你可以这样做:
<ul id='uiID'>
<li id='myLi' onclick="alert(this.parentNode.id)">A</li>
</ul>
回答by Marc B
Javascript is case sensitive for most everything:
Javascript 对大多数情况都区分大小写:
<li id='myLi'>A</li>
^^--- big L, small i
var x = document.getElementById("myLI").parentNode.nodeName;
^^---big L, big I
Since you're using an undefined ID, getElementById will return null for "no match found". Null has no "parentNode", hence your error.
由于您使用的是未定义的 ID,因此 getElementById 将为“未找到匹配项”返回 null。Null 没有“parentNode”,因此您的错误。
回答by Omair
var id = $(this).parent().attr("id");
console.log(id);

