【问题标题】:How can I use javascript to add and remove an element over and over again?如何使用 javascript 一遍又一遍地添加和删除元素?
【发布时间】:2013-04-28 06:21:01
【问题描述】:

第一次发帖。我正在尝试使用 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 中出现同样的情况,但我一直找不到答案。

【问题讨论】:

  • 你在哪里定义yesdombuttonnodombutton
  • 你在哪里定义textOnetextTwo
  • @Alnitak - yesdombuttonnodombuttonmakeButtons() 中定义。
  • @Qantas94Heavy - 抱歉,我打算删除该代码,因为它仅用于添加按钮上显示的文本,现在编辑!

标签: javascript firefox internet-explorer-10 removechild


【解决方案1】:

我的一个朋友提到我有一个范围问题...以下代码使网站按我想要的方式工作。

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);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多