我如何通过onclick在js中的孩子来获取父ID? [英] How can I get parent id by onclick on a child in js?
本文介绍了我如何通过onclick在js中的孩子来获取父ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<div id="rnd()"><button onclick="checkId()">Click</button></div>
当我在JS中通过DOM制作时,我有一个DIV,并且有一个随机ID,他的孩子是这个按钮.
I have a DIV when I make by DOM in JS and has a random ID, his child this button.
我需要单击一个按钮,才能知道父代(DIV)的ID.
I need at the click of a button I can know what the ID of the parent (DIV).
推荐答案
您需要更新函数调用以包括 this
:
You need to update your function call to include this
:
<div id="rnd()"><button onClick="checkId(this)">Click</button></div>
<script>
function checkId(elem)
{
alert(elem.parentNode.id);
}
</script>
或使用javascript添加事件,并为您的按钮提供一个ID,如下所示:
or add the event using javascript and give your button an id like this:
<div id="rnd()"><button id="myBtn">Click</button></div>
<script>
document.getElementById("myBtn").onclick = function(e){
alert(e.target.parentNode.id);
}
</script>
这篇关于我如何通过onclick在js中的孩子来获取父ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文