我正在尝试创建一个通用函数来删除调用它的任何内容。 我的代码如下:
function deletethis(n){
//n is unused in this shortened snippet
this.parentNode.removeChild(this);
}
<button onclick="deletethis(5)">Click to remove</button>
预期行为:按钮被删除。
实际行为:错误无法读取未定义的属性“removeChild”
最佳答案
正如詹姆斯在评论中指出的那样。 this
不会自动传递。试试这个
function deletethis(ele, n){
//n is unused in this shortened snippet
ele.parentNode.removeChild(ele);
}
<button onclick="deletethis(this, 5)">Click to remove</button>
关于javascript - 删除调用 onclick 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56531549/