简体   繁体   English

将第二个项目添加到 div 时,JavaScript 事件处理程序不起作用?

[英]JavaScript event handler not working when second item is added to a div?

So basically when I run this code it adds a button to a div and when you press the button it removes itself as expected.所以基本上当我运行这段代码时,它会向 div 添加一个按钮,当你按下按钮时,它会按预期移除自己。

 document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>' document.getElementById("remove").addEventListener("click", function () { document.getElementById("remove").remove(); });
 <div id="inputdiv"></div>

However when you add two buttons X1 event handler stops working but X2 works fine?但是,当您添加两个按钮时,X1 事件处理程序停止工作但 X2 工作正常?

I believe when the second button is added it some how effects there first button event handler but not sure why?我相信当添加第二个按钮时,它会如何影响第一个按钮事件处理程序,但不确定为什么?

 document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>' document.getElementById("remove").addEventListener("click", function () { document.getElementById("remove").remove(); }); document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove2">X2</button>' document.getElementById("remove2").addEventListener("click", function () { document.getElementById("remove2").remove(); });
 <div id="inputdiv"></div>

innerHTML does not append instead reloads the full DOM. innerHTML不会追加而是重新加载完整的 DOM。 That's why the event does not work.这就是事件不起作用的原因。 You can use insertAdjacentHTML() instead:您可以使用insertAdjacentHTML()代替:

 document.getElementById("inputdiv").innerHTML += '<button type="button" id="remove">X1</button>' document.getElementById("remove").addEventListener("click", function () { document.getElementById("remove").remove(); }); document.getElementById("inputdiv").insertAdjacentHTML('beforeend', '<button type="button" id="remove2">X2</button>'); document.getElementById("remove2").addEventListener("click", function () { document.getElementById("remove2").remove(); });
 <div id="inputdiv"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM