You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现仅点击Delete按钮时触发待办项删除的鼠标点击事件

解决Todo列表点击任意区域触发删除的问题

问题原因

你给整个待办事项列表容器绑定了点击事件,当前事件处理逻辑是:只要点击的元素能找到.list-item祖先,就执行删除操作。这就导致点击条目内的复选框、文本区域等任何位置,都会触发删除。

修复方案

核心是在事件处理函数中先校验点击目标是否为删除按钮,再执行删除逻辑:

  • 通过event.target.closest('.delete')判断点击的元素是否属于删除按钮(兼容按钮内部有子元素的情况)
  • 只有确认点击的是删除按钮时,再定位到对应的.list-item条目并删除

修改后的代码

TypeScript 代码

"use strict";
const todoListElement = document.getElementById('ordered-todo-list');
const form = document.getElementById('todo-form');

todoListElement?.addEventListener("click", todoListEraser);

// 给事件参数添加TypeScript类型注解
function todoListEraser(event: MouseEvent) {
    const target = event.target as HTMLElement;
    // 先判断点击的是否是删除按钮
    const deleteButton = target.closest('.delete');
    if (deleteButton) {
        // 找到对应的待办条目并删除
        const targetItem = deleteButton.closest('.list-item');
        targetItem?.remove();
    }
}

function todoListCreator() {
    // 类型断言为HTMLInputElement,避免类型错误
    const itemInput = document.getElementById('todo-input') as HTMLInputElement;
    const item = itemInput.value;
    
    const templateOfList = document.getElementById('list-item-template')?.content;
    if (!templateOfList) return;
    
    const copyHTML = document.importNode(templateOfList, true);
    const taskText = copyHTML.querySelector('.task-text');
    if (taskText) taskText.textContent = item;
    
    todoListElement?.appendChild(copyHTML);
}

form?.addEventListener("submit", (e) => {
    e.preventDefault();
    const resetInput = document.getElementById('todo-input') as HTMLInputElement;
    resetInput.value = '';
});

HTML 代码(修正了重复ID问题)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles.css">
    <title>To do list</title>
    <link rel="icon" type="image/jpg" href="/images/favicon-pineapple.jpg">
</head>
<body>
<h1 class="title">todos</h1>
<form id="todo-form" onsubmit="todoListCreator()">
    <button id="scrolldown-menu-toggle">˅</button>
    <input type="text" id="todo-input" placeholder="Fill in your plan" maxlength="30">
</form>

<template id="list-item-template">
    <!-- 注意:将id="list-item"改为class,避免生成重复ID -->
    <li class="list-item">
        <input type="checkbox" class="status-toggle" name="form-checkbox">
        <p class="task-text"></p>
        <button class="delete">X</button>
    </li>
</template>

<ol id="ordered-todo-list">
</ol>

<footer class="info">
    <p>Double click to edit a todo.</p>
    <p>Created by Thomas Brom.</p>
</footer>

<script src="main.js"></script>
</body>
</html>

额外说明

  • 原模板中<li>使用了id="list-item",生成多个条目会导致页面出现重复ID,违反HTML规范,已修正为class="list-item"
  • TypeScript中对DOM元素添加类型断言,可以避免不必要的类型错误,提升代码健壮性

内容的提问来源于stack exchange,提问作者thomasquestions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:36:28