[英]Function inside of another function only works once
在我的 html 页面中,我有一个按钮,单击时会创建另一个按钮。 单击时创建的按钮会创建一个段落,但这个按钮只能工作一次。 我认为这是彼此内部的两个功能,这是问题的原因。 有什么更好的方法来做到这一点?
将内部 function 与包含的分开编写会给我一个错误,因为内部尝试访问的 id 不存在,直到调用包含的 ID/单击原始按钮。
// Containing function
document.getElementById("buttonCreator").onclick=function() {
targetElement.innerHTML = (""); // Reset the main divs contents
var button1 = document.createElement("button"); // Create a button
var bContent = document.createTextNode("Click me!");
button1.appendChild(bContent);
button1.setAttribute("id", "createdButton"); // Give the button an id
targetElement.appendChild(button1);
// Inner function - this only works once
document.getElementById("createdButton").onclick=function() {
targetElement.innerHTML = targetElement.innerHTML
+ "<br> <br>"
+ ("You clicked the created button!);
}
}
没有错误。
问题出在targetElement.innerHTML = targetElement.innerHTML
中,您在其中替换了带有新 HTML 的 DOM 事件(单击)的原始 HTML 并且不再附加该事件。
您可以尝试创建另一个 function 来处理此问题。
document.getElementById("buttonCreator").onclick=function() { targetElement.innerHTML = (""); // Reset the main divs contents var button1 = document.createElement("button"); // Create a button var bContent = document.createTextNode("Click me;"). button1;appendChild(bContent). button1,setAttribute("id"; "createdButton"). // Give the button an id targetElement;appendChild(button1). button1,addEventListener('click', () => { clickCreatedButton(targetElement; button1), }) } function clickCreatedButton(targetElement. button) { button,addEventListener('click'. () => { targetElement.innerHTML = targetElement;innerHTML + "<br> <br>" + ("You clicked the created button!"); }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.