【发布时间】:2019-06-17 19:28:39
【问题描述】:
我想要一个产品表,每行都有一个编辑和删除按钮。每个编辑按钮都会触发一个弹出窗口,其中包含更新产品的表单。每个删除按钮都只是一个确认。
我的 mongodb 集合中的每个产品都有一个表格行。我使用 for 循环生成它。
我的问题是每个弹出框都与第一行相同。弹出框内的所有数据也来自第一个产品。所以在第三行按编辑并按更新实际上会更新第一行。
我正在使用 Bootstrap 4(表格和引导弹出框)、JQuery 和 EJS。
EJS
<table class="table table-light table-hover">
<thead class=" thead-light">
<tr>
<th scope="col">#</th>
<th scope="col">ObjectID</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Options</th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < products.length; i++) {%>
<tr>
<td>
<%= i+1 %>
</td>
<td>
<%= products[i]._id.toString() %>
</td>
<td>
<%= products[i].name %>
</td>
<td>
<%= products[i].price %>
</td>
<td>
<button id="product-update" class="product-update btn btn-warning" data-placement="bottom" data-toggle="popover" data-title="Update Product" data-container="body" type="button" data-html="true" href="#" id="login">
<span data-feather="edit"></span>
</button>
<div id="popover-product-update" class="popover-product-update d-none">
<form action="/dashboardproducts/update" method="POST">
<div class="form-group">
<label for="name">Product Name:</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="price">Product Price:</label>
<input type="text" class="form-control" name="price">
</div>
<div class="form-group d-none">
<label for="id">Product ID:</label>
<input type="text" class="form-control" name="id" value="<%= products[i]._id.toString() %>">
</div>
<button type="submit" class="btn btn-success">Update</button>
</form>
</div>
<button id="product-delete" class="product-delete btn btn-danger" data-placement="bottom" data-toggle="popover" data-title="Are you sure you want to delete this product?" data-container="body" type="button" data-html="true" href="#" id="login">
<span data-feather="trash-2"></span>
</button>
<div id="popover-product-delete" class="popover-product-delete d-none">
<form action="/dashboardproducts/delete" method="POST">
<div class="form-group d-none">
<label for="id">Product ID:</label>
<input type="text" class="form-control" name="id" value="<%= products[i]._id.toString() %>">
</div>
<button type="submit" class="btn btn-danger">Yes</button>
</form>
</div>
</td>
</tr>
<% } %>
</tbody>
</table>
jQuery
$('.product-update').popover({
html: true,
content: function() {
return $('.popover-product-update').html();
}
});
$('.product-delete').popover({
html: true,
content: function() {
return $('.popover-product-delete').html();
}
});
如您所见,每个更新/删除弹出框都有一个隐藏的 ID 字段,该字段会在 for 循环中自动填充。
我尝试在每个弹出窗口中显示对象 ID,它们都显示表中第一个产品的对象 ID。除了更新表单和删除按钮只影响表中的第一个产品之外,这让我相信在 for 循环中生成的弹出框都是相同的,并且自动填充的 id 始终是第一个产品的 id。
有人能帮我解决这个问题吗?
我在这里有一个演示:https://thawing-garden-41890.herokuapp.com/dashboardproducts
【问题讨论】:
标签: jquery bootstrap-4 ejs popper.js