如何添加删除待办事项列表中内容的功能?

问题描述 投票:0回答:1

我正在使用express和ejs创建一个待办事项列表。我想在我的待办事项列表中添加功能,当我选中复选框时,我想要该特定内容删除线。 To-Do-List snip

首先,我尝试通过 body-parser 获取复选框的值,将其保存在变量中,然后将其传递到我的 index.ejs 文件。我尝试在 EJS 文件中使用变量 on 但它不起作用。 我最终通过控制台记录了该变量,然后我看到显示的值是“未定义”。

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

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


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


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

app.post('/submit',(req,res)=>{
    const {Item: newData} = req.body;
    const checked = req.body["check"];
    Item.push(newData)
    res.render("index.ejs",{Item,checked})
    console.log(checked)
})
app.listen(port,()=>{
    console.log("Server is running on port",port);
})


<!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>
  </head>
  <body>
    <div class="container">
      <form action="/submit" method="POST">
        <input
          type="text"
          placeholder="New Item"
          name="Item"
          class="input-area"
          required
        />
        <input type="submit" class="btn" value="Add" />
      </form>
    </div>
    <% Item.forEach(item => { %>
    <div class="container-2">
      <input type="checkbox" class="checkBox" name="check" required />
      <%= item %>
    </div>
    <% }) %>
  </body>
</html>

javascript express backend ejs body-parser
1个回答
0
投票

我发现你的代码很难理解,因为你将所有内容都命名为“Item”变量。您应该尝试清楚地命名事物以避免混淆。

也就是说,在 HTML 中,“Item”是第一个块的一个对象(绑定在第 18 行)。该对象应在“checked”键下包含您需要的布尔值。

在 HTML 中输入元素上的

forEach
中,您应该能够执行类似
<%= item.check ? 'checked' : ''%>
的操作,这基本上意味着,如果 item.check 存在并且具有值/为 true,则将“checked”添加到 HTML 输入元素,否则,不要。

© www.soinside.com 2019 - 2024. All rights reserved.