javascript - 如果在 JavaScript 中单击了子项,则删除父项
问题描述
我在创建 ToDoApp 时遇到了问题
如果我单击图标应该删除图标所在的位置。我不能编写一个上升到 span 然后到 li 并删除它的函数。
const input = document.querySelector('input');
const list = document.querySelector('ul');
const reset = document.querySelector('.reset');
const addTask = (e) => {
if (e.keyCode === 13 && input.value.length != 0) {
let value = input.value;
const li = document.createElement('li');
const span = document.createElement('span');
const icon = document.createElement('i');
icon.classList.add('material-icons');
icon.textContent = "highlight_off";
span.appendChild(icon);
li.textContent = value;
// span.setAttribute("onclick", `deleteTask()`);
list.appendChild(li);
li.appendChild(span);
input.value = "";
}
}
const deleteTask = (e) => {
const element = e.target;
console.log(element);
element.currentTarget.parentNode.remove();
}
input.addEventListener('keydown', addTask);
list.addEventListener('click', deleteTask)
<div class="container">
<input type="text" placeholder="Type text and click 'enter'">
<ul>
// Here is created li
</ul>
<button class="reset">CLEAR</button>
</div>
解决方案
使用最近的
const input = document.querySelector('input');
const list = document.querySelector('ul');
const reset = document.querySelector('.reset');
const addTask = (e) => {
if (e.keyCode === 13 && input.value.length != 0) {
let value = input.value;
const li = document.createElement('li');
const span = document.createElement('span');
const icon = document.createElement('i');
icon.classList.add('material-icons');
icon.textContent = "highlight_off";
span.appendChild(icon);
li.textContent = value;
// span.setAttribute("onclick", `deleteTask()`);
list.appendChild(li);
li.appendChild(span);
input.value = "";
}
}
const deleteTask = (e) => {
const element = e.target.closest("li");
console.log(element);
element.remove();
}
input.addEventListener('keydown', addTask);
list.addEventListener('click', deleteTask)
<div class="container">
<input type="text" placeholder="Type text and click 'enter'">
<ul>
// Here is created li
</ul>
<button class="reset">CLEAR</button>
</div>
推荐阅读
- javascript - 如果其数组包含猫鼬中的 id,则选择集合
- python - 使用python的Tic,Tac,Toe中的Minimax算法:递归不会结束
- ssas - 除从切片器 DAX 中选择的项目外,列中项目的不同计数
- visual-studio - CMake 生成的 VS 项目需要 lib 而不是 dll
- session - Drupal 7 忽略模板中的 $_SESSION
- javascript - 在 Javascript 中使用准确的货币值
- c - “传统私钥格式”与 PKCS8
- python - Python:在不依赖枕头库的情况下旋转图像?
- rsyslog - 当 rsyslog (v8.39.0) 无法识别 mmnormalize 时。如何解决这个问题?
- javascript - Javascript 中的登录功能未按预期工作。里面有更多细节