gpt4 book ai didi

javascript - 使用 javascript 删除按钮

转载 作者:行者123 更新时间:2023-12-03 04:55:26 24 4
gpt4 key购买 nike

我试图在单击按钮后删除该按钮(该按钮是在 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();
});

最佳答案

尝试这些改变

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();
});

关于javascript - 使用 javascript 删除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com