在我的 html 页面中,我有一个按钮,单击时会创建另一个按钮。单击该创建的按钮会创建一个段落,但该按钮只能运行一次。我认为这是问题的原因,这是彼此内部的两个函数。更好的方法是什么?
将内部函数与包含函数分开编写会给我一个错误,因为在调用包含函数/单击原始按钮之前,内部函数尝试访问的 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,并且不再附加该事件。
关于javascript - 另一个函数内部的函数只能运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58595567/