删除Div的Javascript函数
Javascript Function to Remove Div
我需要一个可以逐个删除div的函数。我的代码如下所示。在我的代码中,我创建了一个函数,当我单击按钮时创建一个div。而且我不知道如何一个一个地删除div。
请帮我用正确的代码逐个删除div
<html>
<head>
</head>
<body>
<button id="buttonone" onclick="creatediv()">CREATE A DIV</button>
<button id="buttontwo" onlick="removedivider()">Remove DIV </button>
<script>
function creatediv()
{
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("div");
newdiv.setAttribute("id","newdiv");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
//Function to Remove the DIV one by one;
}
</script>
</body>
</html>
<script>
var index = 0;
function creatediv()
{
++index;
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("span");
newdiv.setAttribute("id","newdiv" + index);
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
document.body.removeChild(document.getElementById("newdiv" + index));
--index;
}
</script>
应该可以,我没有测试。
您不是很清楚应该删除哪个div
。此外,在您的代码中,您重复地用相同的id
附加div
s。你不能那样做。
我做了一个快速的例子,删除了首先附加的div
(队列)。我给每个日期一个基于当前时间的id
,但这真的不是必要的。您总是可以删除父div的第一个子div,您要添加这些div
s。
但是,如果您计划将这些div
附加在不一定都在同一父节点下的地方,那么为它们提供唯一的id
并存储这些id
是有用的。