2016-03-01 102 views
-1

我想爲使用JavaScript動態添加的HTML元素添加事件監聽器。 喜歡的東西 我有一個div在我的主頁添加動態添加元素的Addinf事件監聽器 - HTML/JS

<div id="someid"></div> 

,並在其事件偵聽按鈕的點擊作爲

document.getElementById("someid").innerHTML = "<input type='button' id ='ad' value='Add' style='height:30px; width:90px'/>" 
document.getElementById("ad").onclick = notherFunc; 

和功能就像

function notherFunc(){ 
     alert("WORKING") 
} 

但不工作。有沒有辦法將該按鈕綁定到一個函數上?

+0

您的代碼正常工作https://jsfiddle.net/jnwrc5ay/46/ –

回答

1

您需要使用名爲「event delegation」的技術。實質上,您需要將點擊處理程序綁定到確實存在的元素,並查看被點擊的元素是否是您期望的元素。

document.getElementById("someid").addEventListener("click", function (e) { 

    if (e.target.id === "ad") { 
     notherFunc(); 
    } 

});