Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 另一个函数中的函数只工作一次_Javascript_Html - Fatal编程技术网

Javascript 另一个函数中的函数只工作一次

Javascript 另一个函数中的函数只工作一次,javascript,html,Javascript,Html,在我的html页面中,我有一个按钮,在单击时创建另一个按钮。“已创建”按钮在单击时创建一个段落,但此按钮只工作一次。这是两个相互作用的函数,我认为这是问题的原因。有什么更好的方法可以做到这一点 将内部函数与包含函数分开编写会给我一个错误,因为在调用包含函数/单击原始按钮之前,内部函数尝试访问的id不存在 // Containing function document.getElementById("buttonCreator").onclick=function() { target

在我的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!);
    }
}
//包含函数
document.getElementById(“buttonCreator”).onclick=function(){
targetElement.innerHTML=(“”);//重置主divs内容
var button1=document.createElement(“按钮”);//创建一个按钮
var bContent=document.createTextNode(“单击我!”);
按钮1.追加子项(b内容);
button1.setAttribute(“id”,“createdButton”);//给按钮一个id
targetElement.appendChild(按钮1);
//内部功能-此功能只工作一次
document.getElementById(“createdButton”).onclick=function(){
targetElement.innerHTML=targetElement.innerHTML
+“

” +(“您单击了“创建”按钮!); } }

没有错误。

问题出在
targetElement.innerHTML=targetElement.innerHTML
中,您用新的HTML替换附加了DOM事件(单击)的原始HTML,并且不再附加事件。

您可以尝试创建另一个函数来处理此问题

document.getElementById(“buttonCreator”).onclick=function(){
targetElement.innerHTML=(“”);//重置主divs内容
var button1=document.createElement(“按钮”);//创建一个按钮
var bContent=document.createTextNode(“单击我!”);
按钮1.追加子项(b内容);
button1.setAttribute(“id”,“createdButton”);//给按钮一个id
targetElement.appendChild(按钮1);
按钮1.addEventListener('单击',()=>{
单击CreatedButton(targetElement,按钮1);
})
}
函数clickCreatedButton(targetElement,按钮){
按钮。addEventListener('单击',()=>{
targetElement.innerHTML=targetElement.innerHTML
+“

” +(“您单击了“创建”按钮!”); })
}
+(“您单击了“创建”按钮!)这看起来好像缺少引号,还有,为什么是括号?您已经分配给targetElement.innerHTML两次了,可以说是从脚下踢梯子。嘿,伙计们,首先感谢你们的回答。我没有替换innerHtml,而是在DOM中添加了另一个段落,从而解决了这个问题。