用于动态添加元素的Addinf事件侦听器 - HTML / JS

时间:2016-03-01 17:27:24

标签: javascript html dom

我正在尝试为使用JavaScript动态添加的HTML元素添加事件侦听器。 就像是 我的主页上有一个div

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

并单击一个按钮,其eventlistener为

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")
}

但它不起作用。有没有办法用函数绑定该按钮?

1 个答案:

答案 0 :(得分:1)

您需要使用名为&#34; event delegation&#34;的技术。实际上,您需要将单击处理程序绑定到存在的元素,并查看单击的元素是否是您期望的元素。

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

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

});
相关问题