本文旨在帮助开发者理解如何使用 JavaScript 从动态生成的列表中删除特定元素,而不是总是删除最后一个元素。我们将通过修改现有的 `deleteItem` 函数,使其能够识别被点击的元素,并从数组中正确地移除它。本文将提供详细的代码示例和解释,确保你能够轻松地将此功能集成到你的项目中。
原始代码中的 deleteItem 函数试图通过 document.getElementById("close") 获取要删除的元素。然而,getElementById 只能获取页面上 第一个 具有指定 ID 的元素。由于你的列表项是动态生成的,并且可能没有唯一的 ID,因此 deleteItem 函数总是会尝试删除页面上的第一个 "close" 元素,这通常不是你想要删除的列表项。
为了正确删除特定元素,我们需要以下步骤:
以下是修改后的 JavaScript 代码:
let myArray = ["Sugar", "Milk", "Bread", "Apples"];
let list1 = document.querySelector("#itemList");
//This function pushed my array items to create the list
arrayList = (arr) => {
let items = arr.forEach(item => {
let li = document.createElement('li');
li.textContent = item;
li.onclick = deleteItem; // Add onclick event 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")
idElement[0].style.color = "red"
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);
list1.innerHTML = '';
arrayList(myArray)
idSelector()
}
}
//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.innerHTML;
//console.log(clk);
let index = myArray.indexOf(clk);
if (index > -1)
{
myArray.splice(index, 1);
}
list1.innerHTML = '';
arrayList(myArray)
}以下是修改后的 HTML 代码:
Shopping List
关键修改:
返回 -1。通过传递事件对象并使用 event.target 和 indexOf,我们可以准确地识别并删除用户点击的特定列表项。这种方法避免了总是删除最后一个元素的问题,并提供了更直观和用户友好的体验。希望本教程能够帮助你更好地理解 JavaScript 事件处理和数组操作。