我如何使用javascript添加和删除元素一遍又一遍

How can I use javascript to add and remove an element over and over again?

本文关键字:一遍 元素 删除 何使用 javascript 添加      更新时间:2023-09-26

第一次发帖。我试图使用HTML中定义的按钮来调用通过JavaScript创建按钮的函数,而另一个按钮则删除创建的按钮。

HTML:

<div id="thisdiv">
    <input type="button" onclick="makeButtons()" value="Add" />
    <input type="button" onclick="removeButtons()" value="Remove" />
</div>
Javascript:

function makeButtons()
{
var buttonOne=document.createElement("BUTTON");
var buttonTwo=document.createElement("BUTTON");
buttonOne.setAttribute("id", "yesdombutton"); //adds id to button
buttonTwo.setAttribute("id", "nodombutton"); //adds id to button
document.getElementById("thisdiv").appendChild(buttonOne); //appends buttons
document.getElementById("thisdiv").appendChild(buttonTwo);
}
function removeButtons()
{   
var div = document.getElementById("thisdiv");
div.removeChild(yesdombutton);     //this works only once in firefox but >
div.removeChild(nodombutton);      //works over and over in IE
}

作为remove()函数状态下的注释,代码在Firefox中只能工作一次,但在IE10中可以正常工作。工作,我的意思是我可以点击是和否按钮在HTML部分,来回,和JavaScript创建的按钮出现和消失,因为他们应该。

我希望在Firefox中也发生同样的情况,但我一直无法找到答案。

我的一个朋友提到我有一个范围问题…下面的代码使站点按照我想要的方式工作。

Javascript:

function removeButtons()
{
var div = document.getElementById("albumown");
var destroyMe = document.getElementById("yesdombutton");   //This makes it so that
var destroyMeToo = document.getElementById("nodombutton"); //the buttons I want to
                                                           //remove are referenced
div.removeChild(destroyMe);                                //correctly
div.removeChild(destroyMeToo);
}

感谢那些问这个问题的人!一个星期以来,我一直在绞尽脑汁,尝试不同的东西。但是,现在一切都好了。