首页 > 解决方案 > 如果在 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>

标签: javascripthtmlhtml-listsaddeventlistener

解决方案


使用最近的

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>


推荐阅读