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

如何在点击时删除列表中特定项而非最后一项

聖光之護
发布: 2025-10-29 16:39:12
原创
888人浏览过

如何在点击时删除列表中特定项而非最后一项

本文档旨在帮助开发者解决在JavaScript中,点击列表项时总是删除最后一项的问题。我们将通过修改事件处理方式,准确获取被点击元素的索引,并从数组中删除对应项,从而实现点击删除特定列表项的功能。本文提供了详细的代码示例和步骤说明,助你轻松掌握该技巧。

在动态生成列表并希望实现点击删除特定项的功能时,开发者常常会遇到点击任何列表项都只删除最后一项的问题。这通常是由于事件处理方式不正确,导致无法准确获取被点击元素的索引。以下提供一种解决方案,帮助你正确实现点击删除特定列表项的功能。

核心思路:

  1. 修改HTML结构: 将删除按钮添加到每个列表项内部,并为每个按钮绑定点击事件
  2. 修改事件处理函数: 在事件处理函数中,通过event.target获取被点击的元素,进而获取该元素对应的列表项的索引。
  3. 使用splice()方法: 使用splice()方法从数组中删除指定索引的元素。
  4. 重新渲染列表: 删除元素后,重新渲染列表,以反映最新的数据。

详细步骤和代码示例:

1. 修改HTML结构

将删除按钮(或者其他触发删除操作的元素)添加到每个列表项 <li> 内部。并且,将 onclick 事件直接绑定到每个 <li> 元素上,并传入 event 对象。

<ul id="itemList">
  </ul>
登录后复制

在 JavaScript 中动态生成列表项时,将删除按钮添加到每个 <li> 元素中。

2. 修改 JavaScript 代码

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台0
查看详情 序列猴子开放平台

首先,修改 arrayList 函数,使其能够为每个列表项添加点击事件和删除按钮。

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.onclick = deleteItem; // Attach the deleteItem function to the li element
        list1.appendChild(li);
    });
}

arrayList(myArray)
登录后复制

然后,修改 deleteItem 函数,使其能够获取被点击元素的索引,并从数组中删除对应项。

//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);
    }
    arrayList(myArray) // Re-render the list
}
登录后复制

3. 完整代码示例:

<!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>
        <span value="\uOOD7" class="close">
            <ul id="itemList">


            </ul>
        </span>
    </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;
                li.onclick = deleteItem; // Attach the deleteItem function to the li element
                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);
            }
            arrayList(myArray) // Re-render the list
        }
    </script>
</body>

</html>
登录后复制

注意事项:

  • event.target: event.target 属性返回触发事件的元素。在本例中,它返回被点击的 <li> 元素。
  • indexOf(): indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。
  • splice(): splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。 arr.splice(index, 1) 表示从索引 index 处删除 1 个元素。
  • 数据同步: 确保数组 myArray 和列表 itemList 中的数据始终保持同步。每次修改数组后,都要重新渲染列表。

总结:

通过修改HTML结构和JavaScript代码,可以实现点击删除列表中特定项的功能。 关键在于正确获取被点击元素的索引,并使用 splice() 方法从数组中删除对应项。同时,要注意数据同步,确保数组和列表中的数据一致。希望本教程能够帮助你解决相关问题。

以上就是如何在点击时删除列表中特定项而非最后一项的详细内容,更多请关注php中文网其它相关文章!

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

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

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

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