我想删除按钮后,它被点击(该按钮是在JavaScript中创建),并从不同的职位,它表示此代码将工作,但在我的控制台我得到的错误:删除与JavaScript的按钮
Uncaught TypeError: Cannot read property 'remove' of null
at HTMLUnknownElement.<anonymous> (RBrOJeLwYgRM:335)
为什么?帮帮我! 代码:
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
我的代码,激活删除功能:
else if (PaintBrush.crashWith(Finish)) {
PaintBrush.y = 50;
var button = document.createElement("button2");
button.innerHTML = "Level 2";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
GameArena.clear();
GameArena.stop();
button.addEventListener ("click", function() {
startGame2();
document.getElementById("button-2").remove();
});
你是想被据说要删除元素
代码删除'document.createElement(“button2”)'按钮?你是否试图用'button2'标签或'button2'来创建一个元素? – litel
'为什么?'因为你试图访问'null'的'.remove',就像控制台错误说的那样。你在哪里调用'.remove()',你在调用'.remove()',你为什么认为它可能是空? –