0

0

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

花韻仙語

花韻仙語

发布时间:2025-10-29 17:32:21

|

921人浏览过

|

来源于php中文网

原创

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

本文将指导你如何使用 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 函数。

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

    AdsGo AI
    AdsGo AI

    全自动 AI 广告专家,助您在数分钟内完成广告搭建、优化及扩量

    下载
    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 操作和数组操作是实现此功能的基础。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
DOM是什么意思
DOM是什么意思

dom的英文全称是documentobjectmodel,表示文件对象模型,是w3c组织推荐的处理可扩展置标语言的标准编程接口;dom是html文档的内存中对象表示,它提供了使用javascript与网页交互的方式。想了解更多的相关内容,可以阅读本专题下面的文章。

4388

2024.08.14

DOM是什么意思
DOM是什么意思

dom的英文全称是documentobjectmodel,表示文件对象模型,是w3c组织推荐的处理可扩展置标语言的标准编程接口;dom是html文档的内存中对象表示,它提供了使用javascript与网页交互的方式。想了解更多的相关内容,可以阅读本专题下面的文章。

4388

2024.08.14

li是什么元素
li是什么元素

li是HTML标记语言中的一个元素,用于创建列表。li代表列表项,它是ul或ol的子元素,li标签的作用是定义列表中的每个项目。本专题为大家li元素相关的各种文章、以及下载和课程。

438

2023.08.03

PHP 高并发与性能优化
PHP 高并发与性能优化

本专题聚焦 PHP 在高并发场景下的性能优化与系统调优,内容涵盖 Nginx 与 PHP-FPM 优化、Opcode 缓存、Redis/Memcached 应用、异步任务队列、数据库优化、代码性能分析与瓶颈排查。通过实战案例(如高并发接口优化、缓存系统设计、秒杀活动实现),帮助学习者掌握 构建高性能PHP后端系统的核心能力。

115

2025.10.16

PHP 数据库操作与性能优化
PHP 数据库操作与性能优化

本专题聚焦于PHP在数据库开发中的核心应用,详细讲解PDO与MySQLi的使用方法、预处理语句、事务控制与安全防注入策略。同时深入分析SQL查询优化、索引设计、慢查询排查等性能提升手段。通过实战案例帮助开发者构建高效、安全、可扩展的PHP数据库应用系统。

99

2025.11.13

JavaScript 性能优化与前端调优
JavaScript 性能优化与前端调优

本专题系统讲解 JavaScript 性能优化的核心技术,涵盖页面加载优化、异步编程、内存管理、事件代理、代码分割、懒加载、浏览器缓存机制等。通过多个实际项目示例,帮助开发者掌握 如何通过前端调优提升网站性能,减少加载时间,提高用户体验与页面响应速度。

38

2025.12.30

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

114

2026.03.06

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

90

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

136

2026.03.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 1.0万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.7万人学习

CSS教程
CSS教程

共754课时 | 44.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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