点击时移除自身元素

14

我有一个元素是通过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
9个回答

16

在 HTML 的 onclick 中,你需要将 this 传递到函数调用中,这样它才能引用该元素,然后你需要将它作为函数定义的参数使用,否则,如果在函数定义中使用 this,它将只引用 window 对象。

This will work fine

function remove(el) {
  var element = el;
  element.remove();
}
<div id="i" onclick="remove(this)">Sample text</div>


3
为什么要将元素存储在变量中,如果你只是想删除它呢? - ii iml0sto1
4
因为onclick="this.remove()"太过常见。 - Sodj

7

极简解决方案:

<div onclick="this.remove()">Sample text</div>

4
你的删除函数应该像这样。
function remove(elem){
  elem.parentNode.removeChild(elem);
}

你在HTML中传递了一个this,它是HTML标签本身。但是,在js函数中使用this时,它代表的是函数本身,所以试图将js函数的ID用作元素ID会导致错误。请注意区分两者之间的不同。

2

"未捕获的类型错误:无法读取未定义的'删除'属性"

这意味着您尝试删除的对象不存在,因为this.id在任何地方都没有定义,这是非常合理的。

要使用JavaScript正确引用HTML元素,您需要使用document.getElementById()函数。您正在尝试删除的HTML元素的ID是i-因此请尝试document.getElementById("i");

function remove() {
  var element = document.getElementById("i");
  element.remove();
}
<div id="i" onclick="remove(this)">Sample text</div>

另一种更优雅的方式是在回调函数中传递所点击对象的引用。只需添加参数event即可完成此操作。在回调函数内部,可以使用e.target引用该元素。"最初的回答"

function remove(e) {
  var element = e.target;
  element.remove();
}
<div id="i" onclick="remove(event)">Sample text</div>


2
为了匹配您的查询,使用outerHTML将从DOM中删除元素及其组件。
这需要使用document.getElementById()
最初的回答。

function remove(me) {
  document.getElementById(me).outerHTML = ""
}
<div id="i" onclick="remove(this.id)">Sample text</div>

随着帖子的赞数增加,有一个更好的编码实践:

  • 使用3个字符作为元素ID更好。

  • 我们可以通过target.nodeName按类型过滤元素,但类型需要用大写字母写。

“Original Answer”翻译成“最初的回答”。

document.body.addEventListener("mousedown", function(e) {
  console.log(e.target.nodeName, e.target.id)
  if (e.target.nodeName === "DIV"){
    document.getElementById(e.target.id).outerHTML = ""
  }
}, false)
<body>
  <div id="el1">Sample text</div>
  <div id="el2">Sample text</div>
  <div id="el3">Sample text</div>
  <div id="el4">Sample text</div>
  <div id="el5">Sample text</div>
  <div id="el6">Sample text</div>
</body>


0

如果你想在普通的 JS 函数中使用它,你需要将 `this` 绑定到函数上。否则它会默认为 window 对象,普通 js 中的 `this` 指向 window 对象。如果你想使用 `this` 指向调用该函数的对象,则应使用 ()=>{} 箭头函数。

function remove(element) {
   console.log(this) //will log Window Object
  //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>


0

先获取你的元素:

const myDiv = document.querySelector('div');

然后为其添加点击事件监听器,这样当它被点击时,回调方法将被调用,在其中'e.target'充当'this',最后使用remove()将其移除:
myDiv.addEventListener('click', function(e){
  e.target.remove();
});

-1

不要使用内联事件监听器(此示例中按钮上的事件监听器仅用于简化)。

function createDiv() {
  let div = document.createElement('div');
  div.textContent = `Sample text, created on ${new Date()}`;
  div.addEventListener('click', remove);
  document.body.appendChild(div);
}

function remove(e) {
  e.target.remove();
}
<button type="button" onclick="createDiv()">Add a div</button>

如果您无法访问添加监听器的元素,则还可以使用委托监听器:

document.addEventListener('click', remove);

function remove(e) {
  // you need some check here if you don't want any element to be removed on clicking it
  e.target.remove();
}
<div>foo</div>

<div>Sample text</div>


-1
我会这样做,以便缓存您的JavaScript和CSS。只需确保在部署文件时更改文件名(当人们知道您的网站存在时)。

//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q;// for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
function remove(e){
  e.parentNode.removeChild(e);
}
var sample = I('sample');
sample.onclick = function(){
  remove(this);
}
}); // end load
//]]>
/* external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div id='content'>
    <div id='sample'>Sample Text</div>
  </div>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接