本文档旨在指导开发者如何使用 JavaScript 实现从列表中删除特定项的功能,而不是仅仅删除最后一项。我们将分析常见错误,并提供正确的实现方式,包括事件处理、索引查找以及数组操作,并提供完整的代码示例。
初学者在实现列表项删除功能时,经常会遇到点击任何列表项都只删除最后一项的问题。这通常是由于以下原因造成的:
以下是一个正确的实现方式,它解决了上述问题:
HTML 结构:
Shopping List
JavaScript 代码:
let myArray = ["Sugar", "Milk", "Bread", "Apples"];
let list1 = document.querySelector("#itemList");
// This function pushed my array items to create the list
arrayList = (arr) => {
list1.innerHTML = ''; // Clear the list before re-rendering
arr.forEach(item => {
let li = document.createElement('li');
li.textContent = item;
li.addEventListener('click', deleteItem); // Add event listener to each list item
list1.appendChild(li);
});
}
arrayList(myArray);
//This function changed the background color of two of the list items to show that they are sold
const idSelector = () => {
let idElement = document.getElementsByTagName("li");
if (idElement.length > 0) { // Check if elements exist before accessing them
idElement[0].style.color = "red";
if (idElement.length > 3) {
idElement[3].style.color = "red";
}
}
}
idSelector();
//This function uses the user input from the form to add items to the list
updateList = (arr) => {
let blue = document.getElementById("input").value;
if (blue === "") {
alert("Please enter a value if you wish to add something to your list.")
} else {
arr.push(blue);
arrayList(myArray); // Re-render the list after adding
idSelector();
document.getElementById("input").value = ""; // Clear the input field
}
}
//This function is meant to delete the specified item chosen by the user from the shopping list and the array
deleteItem = (event) => {
let clk = event.target.textContent; // Get the text content of the clicked list item
let index = myArray.indexOf(clk);
if (index > -1) {
myArray.splice(index, 1);
}
arrayList(myArray); // Re-render the list after deleting
idSelector();
}代码解释:
(index > -1),则使用 myArray.splice(index, 1) 从数组中删除该元素。 splice() 方法会修改原始数组。通过遵循这些步骤,您可以创建一个能够从列表中删除特定项的 JavaScript 程序。记住,理解每个步骤背后的原理是解决类似问题的关键。