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

如何在Express+EJS开发的待办清单中添加勾选删除线功能?

解决Express+EJS待办清单勾选复选框显示删除线的问题

你的问题核心出在这几点:

  • 复选框不在提交表单范围内,勾选操作根本没触发后端请求,自然拿不到req.body["check"]
  • 所有复选框共用同一个name,就算提交也无法区分是哪条任务被勾选
  • 数据结构只存了任务文本,没记录任务的完成状态

下面是完整修复方案:

1. 重构数据结构

把单纯存文本的数组改成存对象,每个对象包含任务内容和完成状态:

const items = []; // 变量名小写开头,符合JS编码规范

2. 调整Express路由逻辑

添加处理任务状态切换的路由,同时优化添加任务的逻辑:

import express from "express";
import bodyParser from "body-parser";

const app = express();
const port = 3000;
const items = [];

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

app.get('/',(req,res)=>{
    res.render("index.ejs",{ items });
});

// 添加新任务
app.post('/add',(req,res)=>{
    const newItemText = req.body.item;
    items.push({ text: newItemText, completed: false });
    res.redirect('/'); // 重定向避免重复提交
});

// 切换任务完成状态
app.post('/toggle',(req,res)=>{
    const itemIndex = parseInt(req.body.index);
    items[itemIndex].completed = !items[itemIndex].completed;
    res.redirect('/');
});

app.listen(port,()=>{
    console.log("Server is running on port", port);
});

3. 修改EJS模板

给每个待办项的复选框绑定对应任务索引,根据完成状态渲染删除线:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>ToDoList</title>
    <style>
        .completed {
            text-decoration: line-through;
            color: #888;
        }
    </style>
</head>
<body>
    <div class="container">
        <form action="/add" method="POST">
            <input
                type="text"
                placeholder="New Item"
                name="item"
                class="input-area"
                required
            />
            <input type="submit" class="btn" value="Add" />
        </form>
    </div>

    <% items.forEach((item, index) => { %>
    <div class="container-2">
        <form action="/toggle" method="POST">
            <input type="hidden" name="index" value="<%= index %>" />
            <input 
                type="checkbox" 
                class="checkBox" 
                <%= item.completed ? 'checked' : '' %>
                onchange="this.form.submit()"
            />
            <span class="<%= item.completed ? 'completed' : '' %>">
                <%= item.text %>
            </span>
        </form>
    </div>
    <% }) %>
</body>
</html>

关键细节说明:

  • 用隐藏域input[type="hidden"]传递任务索引,让后端知道要修改哪条任务
  • 给复选框加onchange="this.form.submit()",实现勾选时自动提交表单
  • 根据item.completed状态给文本添加completed类,动态显示删除线
  • 添加任务后用res.redirect('/')重定向,避免刷新页面重复创建任务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:05:25