2017-02-24 65 views
0

我想删除按钮后,它被点击(该按钮是在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(); 
}); 
+0

你是想被据说要删除元素

代码删除'document.createElement(“button2”)'按钮?你是否试图用'button2'标签或'button2'来创建一个元素? – litel

+0

'为什么?'因为你试图访问'null'的'.remove',就像控制台错误说的那样。你在哪里调用'.remove()',你在调用'.remove()',你为什么认为它可能是空? –

回答

1

尝试这些变化

PaintBrush.y = 50; 
var button = document.createElement("button"); // remove the "2" 
button.innerHTML = "Level 2"; 
button.id = "button-2"; // add the id to the button 
document.body.appendChild(button); // append to body 
GameArena.clear(); 
GameArena.stop(); 
button.addEventListener ("click", function() { 
    startGame2(); 
    document.getElementById("button-2").remove(); 
}); 
+0

作品!谢谢!真的很有帮助,我将它命名为button2是因为我有一些css来定位它,但是创建了一个名为button-2的css id和样式,这也起作用。再次感谢! – TechEndling

+0

很高兴帮助,如果你想保留“button2”类,你也可以添加它,只需使用: button.className =“button2”; – karkazz