Node.js用户表删除按钮始终跳转至同一用户问题排查
问题分析与解决方案
我一眼就看出问题所在了——你所有的删除按钮都绑定到了同一个表单上!
问题根源
- 重复的表单ID:你给每个用户的表单都设置了
id="myform",但HTML规范要求ID必须是唯一的。当提交按钮指定form="myform"时,浏览器只会找到DOM中第一个匹配该ID的表单(也就是第一个用户Tom Test的表单),所以无论点击哪个按钮,都会触发这个表单的提交。 - 非法的HTML结构:
<form>元素不能直接包裹<tr>标签,<tbody>的直接子元素只能是<tr>。浏览器会自动修正这个错误结构,这也进一步打乱了表单和按钮的关联逻辑。
修复方案
方案1:修正表单结构(推荐)
把每个表单放到对应的<td>里,去掉重复的ID,让提交按钮直接属于当前表单:
<table id="users" class="table table-striped"> <thead> <th>Name</th> <th>Username</th> <th>Created</th> <th>Edit User</th> </thead> <tbody> <% users.forEach(user => { %> <% if (user.enabled == true) { %> <tr> <td><%- user.name %></td> <td><%- user.username %></td> <td><%- user.created_at %></td> <td> <!-- 每个用户对应独立表单,无需重复ID --> <form method="get" action="users/<%- user._id %>"> <input type="submit" value="Remove User"> </form> </td> </tr> <% } %> <% }) %> </tbody> </table>
方案2:用锚点标签替代表单(更简洁)
因为你使用的是GET请求,完全可以用<a>标签代替表单和提交按钮,代码更简洁,也避免了表单相关的问题:
<table id="users" class="table table-striped"> <thead> <th>Name</th> <th>Username</th> <th>Created</th> <th>Edit User</th> </thead> <tbody> <% users.forEach(user => { %> <% if (user.enabled == true) { %> <tr> <td><%- user.name %></td> <td><%- user.username %></td> <td><%- user.created_at %></td> <td> <a href="/users/<%- user._id %>" class="btn btn-default">Remove User</a> </td> </tr> <% } %> <% }) %> </tbody> </table>
额外提示
- 确认你的后端路由
/users/:id的处理逻辑是正确的,当前问题主要出在前端模板层面。 - 以后写HTML时要注意ID的唯一性和标签嵌套规范,避免这类容易犯的低级错误。
内容的提问来源于stack exchange,提问作者Thomas Hutton
相关产品推荐
相关产品推荐

