我有一个元素是通过JavaScript添加到我的HTML文档中的。我正在尝试在单击该元素时将其删除。目前我不知道该元素的ID,只是暂时包含了一个示例ID。
我已经尝试查看这里的答案(Creating an element that can remove it self?)并尝试使用此处提供的方法(Javascript: How to make a Control send itself in a method)来引用该元素但都没有成功。
以下是我当前的代码。
function remove() {
var element = this.id;
//I have also tried using document.getElementByID(this.id)
element.remove();
//I have also tried using element.parentNode.removeChild(element); to remove the element.
}
<div id="i" onclick="remove(this)">Sample text</div>
我不确定我做错了什么,但这是一直出现的错误。
"未捕获的类型错误:无法读取未定义的属性 'remove'"
this.id
并尝试删除它。应该使用this.remove()
,但如果你在意的话,这在 IE 中不起作用。另外,你应该学会将 JavaScript 与 HTML 分离开来。 - StackSlave