使用 javascript 删除按钮
2017-02-24
5059
我尝试在单击按钮后将其删除(该按钮是在 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();
});
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();
});
Luis Carlos Arellano Ochoa
2017-02-24