删除待办事项列表项Node.js Express EJS



无法通过EJS点击html按钮从Node.js数组中删除每个列表项,并表示:

我认为我应该在每个列表元素旁边放一个html按钮,然后从Node.js "tasks"数组。

我不知道的是如何使用express告诉EJS和Node.js之间要删除的确切元素。

  • app.js
// IMPORT MODULES
// npm init -y
// npm i express ejs
const express = require('express');
const ejs = require('ejs');
// SETUP
const app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
// DEFINE VARIABLES
let tasks = ['eat', 'sleep'];
let task = '';
// ROUTES
app.get('/', (req, res) => {
res.render('index', { tasks: tasks });
});
app.post('/', (req, res) => {
// HANDLE form POST REQUEST
tasks.push(req.body.addedTask);
res.redirect('/');
});
// PORT
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
  • index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- TODO LIST -->
<ul>
<% tasks.forEach((task) => { %>
<li><%= task %></li>
<% }); %>
</ul>
<!-- ADD TASK -->
<form action="/" method="post">
<input type="text" name="addedTask" placeholder="New Task" />
<button type="submit">Add Task</button>
</form>
</body>
</html>

使用(In index.ejs)将删除按钮绑定到待办事项列表项

<button class="deleteItemBtn" type="submit" name="delete" **value="<%= itemList[i] %>"**>x</button>

,每次点击它的时候,(request .body.delete)会给出名称。,然后从数组中删除该元素并重定向。

app.post('/',function(req,res){
// DELETEbtn
if(req.body.delete){

const index = items.indexOf(req.body.delete); 
if (index > -1) { // only splice array when item is found
items.splice(index, 1);
}
}
//items is my array where I'm storing the newly added to-do list items.
res.redirect('/');
});