You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为待办列表中每个新增的li元素添加删除按钮?

Solution: Add Delete Buttons to New To-Do Items

Hey there! Let's get those delete buttons working for every new list item you add. I'll walk through what went wrong with your previous attempts and share the fixed code to get this running smoothly.

Key Issues in Your Original Code

  • You had a syntax error when creating the delete button: deleteButton.appendChild.createTextNode("delete); should be deleteButton.appendChild(document.createTextNode("delete")); (missing document. and a closing quote).
  • Your deleteBtn function wasn't properly binding click events to buttons, and the this keyword wasn't targeting the right element.
  • New list items weren't getting buttons attached at the time of creation.

Fixed Full Code

HTML

<input id="userinput" type="text" placeholder="enter list item here">
<button id="enter">Add</button>
<ul id="myUL">
  <li>eggs</li><button class="delete-btn">delete</button>
  <li>milk</li><button class="delete-btn">delete</button>
  <li>tacos</li><button class="delete-btn">delete</button>
</ul>

(Note: Swapped the unique btn1 ID for a reusable delete-btn class—IDs should only be used once per page!)

CSS

ul li.checked {
  text-decoration: line-through;
}

.delete-btn {
  margin-left: 10px;
  padding: 2px 8px;
  cursor: pointer;
  /* Add any extra styling you want here */
}

JavaScript

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");

// Toggle strikethrough when clicking list items
ul.addEventListener("click", function(ev) {
  if (ev.target.tagName === "LI") {
    ev.target.classList.toggle('checked');
  }
}, false);

// Helper to get input length
function inputLength() {
  return input.value.length;
}

// Delete the corresponding list item and button
function deleteListItem(event) {
  const clickedButton = event.target;
  const listItemToDelete = clickedButton.previousElementSibling;
  // Remove both the list item and its button
  listItemToDelete.remove();
  clickedButton.remove();
}

// Create a new list item + its delete button
function createListElement() {
  // Make the list item
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);

  // Make the delete button
  var deleteBtn = document.createElement("button");
  deleteBtn.className = "delete-btn";
  deleteBtn.appendChild(document.createTextNode("delete"));
  // Bind the delete function to this button's click event
  deleteBtn.addEventListener("click", deleteListItem);
  ul.appendChild(deleteBtn);

  // Clear the input field
  input.value = "";
}

// Add item when clicking the "Add" button
function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}

// Add item when pressing Enter
function addListAfterKeypress(event) {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

// Set up existing delete buttons to work
document.querySelectorAll(".delete-btn").forEach(btn => {
  btn.addEventListener("click", deleteListItem);
});

// Attach main event listeners
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);

What Changed?

  1. Reusable Button Class: Using delete-btn class lets us style and target all delete buttons consistently.
  2. Proper Button Creation: Now every new list item gets its own delete button in the createListElement function, with the delete logic bound directly to it.
  3. Targeted Deletion: The deleteListItem function uses event.target to find the clicked button, then removes both the button and its adjacent list item.
  4. Initialize Existing Buttons: We loop through all pre-existing delete buttons and bind the delete function to them, so they work too.
  5. Fixed Syntax Errors: Corrected the broken createTextNode call to use proper syntax.

This setup will give every new list item a functional delete button, and fix the existing ones to work as expected!

内容的提问来源于stack exchange,提问作者Trevor Davlin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:39:18