Javascript 我如何通过 js 中的 onclick Child 获取父 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42213858/
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
how i get parent id by onclick Child in js
提问by akosem
<div id="rnd()"><button onclick="checkId()">Click</button></div>
I have a DIV when I make by DOM in JS and has a random ID, his child this button. I need at the click of a button I can know what the ID of the parent (DIV)
当我在 JS 中通过 DOM 制作时,我有一个 DIV 并且有一个随机 ID,他的孩子这个按钮。我需要单击一个按钮,我可以知道父级 (DIV) 的 ID
回答by Nermien Barakat
You need to update your function call to include this:
您需要更新您的函数调用以包括this:
<div id="rnd()"><button onClick="checkId(this)">Click</button></div>
<script>
function checkId(elem)
{
alert(elem.parentNode.id);
}
</script>
or add the event using javascript and give your button an id like this:
或使用 javascript 添加事件并为您的按钮指定一个 id,如下所示:
<div id="rnd()"><button id="myBtn">Click</button></div>
<script>
document.getElementById("myBtn").onclick = function(e){
alert(e.target.parentNode.id);
}
</script>
回答by Liam's musings
You should update the function to take in 'this' So like the following:
您应该更新函数以接收“this”,如下所示:
<div id="rnd()"><button onclick="checkId(this)">Click</button></div>
Then within the checkIdfunction you should have the following:
然后在checkId函数中你应该有以下内容:
var parentDiv = this.parentNode;
var id = parentDiv.getAttribute("id");
回答by Bojan
One way would be to assign it a class and then just use jQuery to get the id such as this:
一种方法是为其分配一个类,然后仅使用 jQuery 来获取 id,例如:
$('.check-id').on('click', function(){
alert($(this).parent().attr('id'));
});
Your div would look like this:
你的 div 看起来像这样:
<div id="rnd()"><button class="check-id">Click</button></div>
With the above approach you can have many buttons and divs and this would work. You just have to make sure to assign a check-id class to the button.
使用上述方法,您可以拥有许多按钮和 div,这将起作用。您只需要确保为按钮分配一个 check-id 类。

