尽管没有错误,RemoveChild仍然无法正常工作

时间:2018-03-31 07:52:08

标签: javascript logic removechild

var disP = document.getElementById("display");
var num = 0;
document.getElementById("plus").addEventListener("click",function(){
    num++;
    var newDiv = document.createElement("div");
    var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);
    newDiv.style.backgroundColor = "rgb("+r+","+g+","+b+")";
    newDiv.id = "newDiv" + num;
    newDiv.style.width = 100 + "px";
    newDiv.style.height = 100 + "px";
    newDiv.style.position= "relative";
    newDiv.style.display = "inline-block";
    disP.appendChild(newDiv);
    

});

disP.addEventListener("click",function(){
    var newDiv = document.createElement("div");
    disP.appendChild(newDiv);
    disP.removeChild(newDiv);
    
});
#ctrl2 #plus {
    background-color:rgb(128,128,128);
    color:white;
}
<div id="preview">
</div>

<div id="ctrl2">
   <button id="plus" value="+" type="button">+</button> <span>|</span>
</div>

<div id=display></div>

嗨,我正在尝试创建一个函数,我可以通过单击div(框)删除任何单个div(框),无论顺序如何。我没有错,但没有发生任何事情。我将不胜感激任何提示和帮助!

P.S我们被告知在学校使用“RemoveChild()”来完成这项工作而不依赖于其他方法,但我也对其他选项持开放态度。

1 个答案:

答案 0 :(得分:0)

disP侦听器提供事件的参数,以便您可以识别事件的目标(单击的方块),这样您就可以删除单击的方块:

var disP = document.getElementById("display");
var num = 0;
document.getElementById("plus").addEventListener("click",function(){
    num++;
    var newDiv = document.createElement("div");
    var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);
    newDiv.style.backgroundColor = "rgb("+r+","+g+","+b+")";
    newDiv.id = "newDiv" + num;
    newDiv.style.width = 100 + "px";
    newDiv.style.height = 100 + "px";
    newDiv.style.position= "relative";
    newDiv.style.display = "inline-block";
    disP.appendChild(newDiv);
});

disP.addEventListener('click', e => {
  if (e.target !== disP) e.target.remove();
});
#ctrl2 #plus {
    background-color:rgb(128,128,128);
    color:white;
}
<div id="preview">
</div>

<div id="ctrl2">
   <button id="plus" value="+" type="button">+</button> <span>|</span>
</div>

<div id=display></div>

.remove().removeChild稍微冗长并达到同样的效果)