首页 > 解决方案 > 如何添加一个EventListener,在点击后删除一个li?

问题描述

到目前为止,这是我的代码:

const list = document.getElementById("list")
const enter = document.getElementById("enter")

enter.addEventListener("click", add => {
  var input = document.getElementById("form").value
  var node = document.createElement("LI")
  var text = document.createTextNode(input)
  node.appendChild(text)
  list.appendChild(node)
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>
  <h1>To-Do:</h1>
  <ul id="list">
    <li>Hello</li>
    <li>This is</li>
    <li>A test</li>
  </ul>
  <div class="input">
    <input id="form" type="text"></input>
    <button id="enter">Add</button>
  </div>

  <script src="app.js"></script>
</body>

</html>

单击添加按钮时,我已经能够添加列表元素,但我不知道如何将 EventListener 添加到每个单独的 li 元素。

标签: javascriptaddeventlistener

解决方案


你可以做的是:

  1. 将一个事件绑定到容器(列表)
  2. 确保单击的元素(目标)是您想要的(例如,一个 LI)
  3. remove()那个元素,如果是这样

这可以通过以下方式完成:

document.querySelector('#list').addEventListener('click', function({target}) {
  if (target.matches('li'))
    target.remove()
}, false);

工作示例

const list = document.getElementById("list")
const enter = document.getElementById("enter")

enter.addEventListener("click", add => {
  var input = document.getElementById("form").value
  var node = document.createElement("li")
  var text = document.createTextNode(input)
  node.appendChild(text)
  list.appendChild(node)
})


document.querySelector('#list').addEventListener('click', function({target}) {
  if (target.matches('li'))
    target.remove()
}, false);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>
  <h1>To-Do:</h1>
  <ul id="list">
    <li>Hello</li>
    <li>This is</li>
    <li>A test</li>
  </ul>
  <div class="input">
    <input id="form" type="text" />
    <button id="enter">Add</button>
  </div>

  <script src="app.js"></script>
</body>

</html>


推荐阅读