Javascript-函数只工作一次,但不会再工作

Javascript-函数只工作一次,但不会再工作,javascript,Javascript,我正在构建一个非常简单的lightbox脚本;单击按钮时,将创建灯箱。单击灯箱背景时,它将被删除 第一次调用该函数时,它工作正常。点击按钮,灯箱显示,点击灯箱,灯箱消失。但是,如果再次尝试单击该按钮,则不会发生任何事情-不会调用div。没有控制台错误或任何东西,不知道问题出在哪里 JSFIDDLE 代码 function closeLightBox(){ document.body.removeChild(lightBox); } function createElem(){

我正在构建一个非常简单的lightbox脚本;单击按钮时,将创建灯箱。单击灯箱背景时,它将被删除

第一次调用该函数时,它工作正常。点击按钮,灯箱显示,点击灯箱,灯箱消失。但是,如果再次尝试单击该按钮,则不会发生任何事情-不会调用div。没有控制台错误或任何东西,不知道问题出在哪里

JSFIDDLE

代码

function closeLightBox(){
        document.body.removeChild(lightBox);
}

function createElem(){
    var elem = "<div id='lightBox'></div>";
    var bodyElem = document.body;
        bodyElem.innerHTML = elem + bodyElem.innerHTML;
    var lightBox = document.getElementById("lightBox");
        lightBox.style.width = "100%";
        lightBox.style.height = "800px";
        lightBox.style.backgroundColor = "rgba(0,0,0,.5)";
        lightBox.onclick = function(){
            closeLightBox();
        }
}
var button = document.getElementsByClassName("btn");
    for (var i = 0; i<button.length; i++){
        button[i].onclick = function(){
            createElem();
        }
    }
函数closeLightBox(){
document.body.removeChild(lightBox);
}
函数createElem(){
var elem=“”;
var bodyElem=document.body;
bodyElem.innerHTML=elem+bodyElem.innerHTML;
var lightBox=document.getElementById(“lightBox”);
lightBox.style.width=“100%”;
lightBox.style.height=“800px”;
lightBox.style.backgroundColor=“rgba(0,0,0,5)”;
lightBox.onclick=函数(){
closeLightBox();
}
}
var按钮=document.getElementsByClassName(“btn”);

对于(var i=0;i不要在
innerHTML
前加前缀;这会使浏览器重新解析HTML并重新创建每个DOM元素,从而在过程中丢失事件处理程序。相反,请使用
document.createElement

var lightBox = document.createElement('div');
document.body.insertBefore(lightBox, document.body.firstChild);
此外,内联
关闭lightbox

lightBox.onclick = function() {
    document.body.removeChild(lightBox);
}

不要在
innerHTML
前加前缀;这会使浏览器重新解析HTML并重新创建每个DOM元素,从而在过程中丢失事件处理程序。相反,请使用
document.createElement

var lightBox = document.createElement('div');
document.body.insertBefore(lightBox, document.body.firstChild);
此外,内联
关闭lightbox

lightBox.onclick = function() {
    document.body.removeChild(lightBox);
}

啊,以前从没听说过
createElement
(JS新手)。只需查看文档,非常简单,非常有意义。谢谢!内联
closeLightBox
只是为了简化代码,还是它实际上在某种程度上导致了问题?@Jascination:嗯,以前,您在
closeLightBox
中使用了
lightBox
是变量decla的名称在
createElem
中为红色,因此在
closeLightBox
中无法访问它。它正好适合您,因为
div
id
也是
lightBox
,但在我的示例中,我停止给它一个
id
,因此它必须内联,以便变量仍然可以访问。明白了。为帮助伙伴干杯.Ah,以前没有听说过
createElement
(JS新手)。只需查看文档,非常简单,非常有意义。谢谢!内联
closeLightBox
只是为了简化代码,还是它实际上在某种程度上导致了问题?@Jascination:嗯,以前,您在
closeLightBox
中使用了
lightBox
是变量decla的名称在
createElem
中为红色,因此在
closeLightBox
中无法访问它。它正好适合您,因为
div
id
也是
lightBox
,但在我的示例中,我停止给它一个
id
,因此它必须内联,以便变量仍然可以访问。明白了。为帮助伙伴干杯.