javascript - 如何添加一个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 元素。
解决方案
你可以做的是:
- 将一个事件绑定到容器(列表)
- 确保单击的元素(目标)是您想要的(例如,一个 LI)
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>
推荐阅读
- ruby-on-rails - Zoho CRM api v2 每个模块的必填字段列表
- javascript - 如何使用 writeFileSync 将 JSON 数据保存在文件中?
- php - 与 .php 文件相比,在 .env 文件中存储信息有什么优势?
- javascript - 在 ES6 React .JS 中使用 Async/Await
- java - 我如何获得多个由 ; 分隔的双输入 从一个 JtextField 并将它们存储在一个数组中?
- r - 如何将 FeatureCollection 中的 geojson 数据加载到 data.frame 中?
- java - Android Java - EditText,appendText 到 inputType Number
- java - Java 将输入追加到文件
- c# - c#文本到int64表示
- javascript - JavaScript 私有成员 - 没有第 3 阶段预设