2017-02-13 84 views
0
<div id="rnd()"><button onclick="checkId()">Click</button></div> 

我有一個DIV,當我由JS製作的DOM,並有一個隨機ID,他的孩子這個按鈕。 我需要一個按鈕的點擊我能知道什麼叫父的ID(DIV)我如何獲得父母id由onclick孩子在js

+1

你的問題不清楚;你能改說嗎? –

回答

0

一種方法是爲其指定一個類,然後只需使用jQuery來獲取ID像這樣:

$('.check-id').on('click', function(){ 
    alert($(this).parent().attr('id')); 
}); 

你的div應該是這樣的:

<div id="rnd()"><button class="check-id">Click</button></div> 

通過上述方法,你可以有很多按鈕和div的,這是可行的。你只需要確保爲按鈕分配一個check-id類。

1

您應該更新的功能,採取「這個」所以,像下面這樣:

<div id="rnd()"><button onclick="checkId(this)">Click</button></div> 

然後checkId函數中,你應該具備以下條件:

var parentDiv = this.parentNode; 
var id = parentDiv.getAttribute("id"); 
2

你需要更新你的函數調用包含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 a id like like:

<div id="rnd()"><button id="myBtn">Click</button></div> 
<script> 
    document.getElementById("myBtn").onclick = function(e){ 
     alert(e.target.parentNode.id); 
    } 
</script> 
相關問題