首页 > web前端 > js教程 > 正文

使用 JavaScript 从列表中删除指定元素

花韻仙語
发布: 2025-10-29 17:32:21
原创
921人浏览过

使用 javascript 从列表中删除指定元素

本文将指导你如何使用 JavaScript 从一个动态生成的列表中删除指定的元素,而不仅仅是最后一个元素。通过修改 `deleteItem` 函数,我们将能够获取点击事件的目标元素,找到它在数组中的索引,并将其从数组和列表中移除。

在网页开发中,经常需要动态地操作列表,例如添加、删除元素。本教程将重点介绍如何使用 JavaScript 实现点击列表项删除该项的功能。核心在于如何准确地获取被点击的元素,并从数据源(数组)中移除对应的项,同时更新页面显示。

HTML 结构调整

首先,我们需要修改 HTML 结构,确保每个列表项都能触发 deleteItem 函数,并传递事件对象 event。 关键是将 onclick 事件直接绑定到每个列表项

  • 元素上,而不是在
      元素之外。同时,需要将删除按钮(例如 "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 函数。

    1. arrayList 函数: 修改 arrayList 函数,使得每个列表项都包含一个删除按钮,并将 onclick 事件绑定到该按钮上。

      通义灵码
      通义灵码

      阿里云出品的一款基于通义大模型的智能编码辅助工具,提供代码智能生成、研发智能问答能力

      通义灵码 304
      查看详情 通义灵码
      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 = '&times;'; // Use &times; 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)
      登录后复制
    2. 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
      }
      登录后复制
    3. 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
      }
      登录后复制
    4. 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 = '&times;'; // Use &times; 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 操作和数组操作是实现此功能的基础。

  • 以上就是使用 JavaScript 从列表中删除指定元素的详细内容,更多请关注php中文网其它相关文章!

    最佳 Windows 性能的顶级免费优化软件
    最佳 Windows 性能的顶级免费优化软件

    每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

    下载
    来源:php中文网
    本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
    最新问题
    开源免费商场系统广告
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送

    Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号