
本文将指导你如何使用 javaScript 从一个动态生成的列表中删除指定的元素,而不仅仅是最后一个元素。通过修改 `deleteItem` 函数,我们将能够获取点击事件的目标元素,找到它在数组中的索引,并将其从数组和列表中移除。
在网页开发中,经常需要动态地操作列表,例如添加、删除元素。本教程将重点介绍如何使用 javascript 实现点击列表项删除该项的功能。核心在于如何准确地获取被点击的元素,并从数据源(数组)中移除对应的项,同时更新页面显示。
html 结构调整
首先,我们需要修改 HTML 结构,确保每个列表项都能触发 deleteItem 函数,并传递事件对象 Event。 关键是将 onclick 事件直接绑定到每个列表项 <li> 元素上,而不是在 <ul> 元素之外。同时,需要将删除按钮(例如 “x”)添加到每个列表项中。
立即学习“Java免费学习笔记(深入)”;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shopping List</title> <!-- Link google Font --> <link href="https://fonts.googleapis.com/css2?family=Nunito&display=swap" rel="stylesheet"> <!-- External CSS link--> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <div class="container"> <h2>Shopping List</h2> <div class="header"> <input type="text" id="input" placeholder="Item"> <span onclick="updateList(myArray)" id="addBtn"><button>Add Item</button></span> </div> <ul id="itemList"> </ul> </div> <script src="mainForTask2.js"></script> </body> </html>
JavaScript 代码修改
接下来,修改 JavaScript 代码以实现正确的功能。关键在于 arrayList 函数和 deleteItem 函数。
-
arrayList 函数: 修改 arrayList 函数,使得每个列表项都包含一个删除按钮,并将 onclick 事件绑定到该按钮上。
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; let span = document.createElement('span'); span.innerHTML = '×'; // Use × for the "x" symbol span.onclick = function(event) { // Wrap the function in an anonymous function deleteItem(item); // Pass the item itself to deleteItem event.stopPropagation(); // Stop the event from bubbling up to the li }; li.appendChild(span); list1.appendChild(li); }); } arrayList(myArray)
-
deleteItem 函数: 修改 deleteItem 函数,使其接收要删除的项作为参数,并使用 indexOf 方法找到该项在数组中的索引,然后使用 splice 方法将其从数组中删除。
//This function is meant to delete the specified item chosen by the user from the shopping list and the array deleteItem = (item) => { let index = myArray.indexOf(item); if (index > -1) { myArray.splice(index, 1); } arrayList(myArray); // Re-render the list after deleting the item } -
updateList 函数: 确保 updateList 函数在添加新项后重新渲染列表。
//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 the item idSelector() } document.getElementById("input").value = ""; // Clear the input field } -
idSelector 函数: 确保 idSelector 函数在重新渲染列表后仍然能够正确地应用样式。
//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) { idElement[0].style.color = "red"; } if (idElement.length > 3) { idElement[3].style.color = "red"; } } idSelector()
完整代码示例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shopping List</title> <!-- Link Google Font --> <link href="https://fonts.googleapis.com/css2?family=Nunito&display=swap" rel="stylesheet"> <!-- External CSS link--> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <div class="container"> <h2>Shopping List</h2> <div class="header"> <input type="text" id="input" placeholder="Item"> <span onclick="updateList(myArray)" id="addBtn"><button>Add Item</button></span> </div> <ul id="itemList"> </ul> </div> <script> //This is a javascript program which added the items in my array to an unordered list 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; let span = document.createElement('span'); span.innerHTML = '×'; // Use × for the "x" symbol span.onclick = function(event) { // Wrap the function in an anonymous function deleteItem(item); // Pass the item itself to deleteItem event.stopPropagation(); // Stop the event from bubbling up to the li }; li.appendChild(span); 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) { 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 the item 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 = (item) => { let index = myArray.indexOf(item); if (index > -1) { myArray.splice(index, 1); } arrayList(myArray); // Re-render the list after deleting the item } </script> </body> </html>
注意事项
- 错误处理: 增加错误处理机制,例如检查 indexOf 是否返回 -1 (表示未找到元素)。
- 性能优化: 对于大型列表,频繁的 dom 操作可能会影响性能。可以考虑使用虚拟 DOM 或其他优化技术。
- 用户体验: 可以添加删除确认提示,防止用户误删。
- CSS 样式: 可以添加 CSS 样式来美化删除按钮。
总结
通过本教程,你学习了如何使用 JavaScript 从动态生成的列表中删除指定的元素。关键在于正确地获取被点击的元素,并从数据源(数组)中移除对应的项,同时更新页面显示。 记住,理解事件冒泡、DOM 操作和数组操作是实现此功能的基础。


