app.get('/delete', function(req, res, next) {
var id = req.query.id;
console.log(id);
MongoClient.connect(dburl, function(err, db) {
if(err) { throw err; }
db.collection('shopping_list', function(err, products) {
products.deleteOne({_id: mongodb.ObjectID(id)});
if (err){
throw err;
}else{
//console.log("deleted");
db.close();
}
});
});
});

<body>
<h1> Shopping List </h1>
<img src="images/cart.png" id="cart">
<div class="text">
<input type="search" placeholder="Find" id="find"/>
<a href="http://www.google.com"><input type="submit" id="find" value="Search" style="background-color: #a3a3c2 ;color:white; width:170px;"></a>
</div>
<form action="/add" method="POST">
<div class="f">
<a href="http://www.facebook.com"><img src="images/fc.jpg" class="follow"></a>
<a href="http://www.twitter.com"><img src="images/twt.jpg" class="follow"></a>
<a href="http://www.instgram.com"><img src="images/ins1.jpg" class="follow"></a>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<label style="margin-left: 20px;">Shopping item</label>            
<label>Quantity</label>
</div>
</div>
<div class="row">
<div class="col-md-8">
<input type="text" id="item" name="item"/>    
<input type="text" id="quan" name="quan"/>    
<input type="submit" id="submit" value="Add item" style="background-color: #a3a3c2 ; color:white; width:170px;" />
</div>
</div>
</div>
</form>
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="tbody">
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</table>
</div>
</div>
</div>
<button id="btn" style="background-color: #a3a3c2 ; color:white; width:170px; margin-left:807px; margin-top:30px;">Clear</button>
<script>
$(function() {
// GET
$.ajax({
url: '/render',
type: 'get',
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.length; i++) {
var trHTML = '';
trHTML += '<tr>';
trHTML += '<td style="display:none" id="id">' +data[i]._id +'</td>';
trHTML += '<td >' + data[i].item + '</td>';
trHTML += '<td >' + data[i].quantity + '</td>';
trHTML += '<td >' + '<button class="delete-button" style="background-color: #a3a3c2 ; color:white; width:170px; margin-left:370px;">Delete</button>' + '</td>';
trHTML += '</tr>';
$('#tbody').append(trHTML);
}
}
});
$(document).ready(function(){
$('table').on('click', '.delete-button', function() {
alert("Confirm delete");
var id=$('#id').html();
console.log(id);
//var rowEl = $(this).closest('tr');
//var id = rowEl.find('.id').text();*/
$.ajax({
url: '/delete',
type: 'get',
dataType: 'json',
data:{id:id},
success: function(data) {
alert("deleted");
//$(this).closest('tr').remove();
}
});
});
});
&#13;
每次使用删除按钮时,数据库顶部的项目都会被删除,但我希望删除特定项目。 因为我为每个项目提供单独的删除按钮,我也面临同样的问题。
答案 0 :(得分:0)
这一行是问题所在:
var id=$('#id').html();
因为您有多个ID为“id”的单元格,所以此作业会选择第一个单元格。将其更改为:
var id = $(this).parent().siblings('#id').text();
将'id'单元格的内容与删除按钮放在同一行。