【发布时间】:2018-03-23 22:55:09
【问题描述】:
当我按下特定元素的删除按钮时,我的删除功能只删除第一个元素,是吗? list.pug(我的视图文件)
ul
each sport_list in sports_list
li(class='form'): a(href='/sport/'+sport_list.name) #{sport_list.name}
form.form-horizontal(class='delete')
input(type='hidden', name='_csrf', value=_csrf id='_csrf')
input(type='hidden', name='id', value=sport_list.id id='id')
.form-group
.col-sm-offset-3.col-sm-7
button.btn.btn-success(type='submit' class='form')
i.fa.fa-trash-o
| Delete
else
li There are no Sport
main.js(我的主 js 库文件)
$(function() {
$('.form').each(function() {
$(this).click(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: '/deleteSport' + $("#id").val(),
data: {_csrf: $("#_csrf").val(), id: $("#id").val()}
// success: function(result) {
// // Do something with the result
// console.log('succesfully deleted'+result);
// }
})
.done(function (json) {
console.log($("#id").val())
console.log(json);
$('.form').show();
});
}); //missing ); here!
});
});
sport.js(我的控制器js)
exports.deleteSport = (req, res) => {
Sport.findByIdAndRemove({_id: req.body.id}, function(err, sport) {
console.log(err,sport)
if (err) {
req.flash('errors', {msg: 'Something wrong'})
}
//res.redirect('/listsports');
res.json({error:err,sport:sport});
})
};
app.js(我的 app.js 文件)
app.post('/deleteSport:id', sportController.deleteSport);
谁能告诉我我犯了什么错误?
【问题讨论】:
-
不确定这与“仅删除第一个元素”(无论是什么意思)有什么关系,但
.findByIdAndRemove()提供的参数不正确。应该是Sport.findByIdAndRemove(req.params.id,function(err, sport) {。这意味着只是值而不是Object(这将是findOneAndRemove())和req.params.id而不是req.body.id,因为id在 URL 中而不是正文中。 -
@NeilLunn 现在也在删除唯一的第一个元素,但点击了第二个元素
-
除了纠正明显的错误外,我还指出您的“问题”并没有真正提出可重复的案例或展示人们可以自己“调试”的任何内容。在这里提问时,您确实需要这样做。至于“更明显的错误”,
$("#id")在选择器中带有#的东西是“唯一的”。因此,您不可能在一个页面上拥有多个由此标识的元素,如果这样做,则只会选择“第一个”。听起来您需要在标记中使用唯一标识符,或者单击处理程序应附加到特定元素 -
但是
$('.form').each(function()对于对象的每个元素,那么为什么不选择............? -
您可能在
.each()中工作,但您发送的值是$("#id").val(),它只是整个页面上的一个元素。您可能打算将事物命名为id="id_1"和id="id_2"等等,并使用标记为.form或其他名称的元素中的索引。但是您不能在标记中使用带有id="id"的多个东西并期望它能够工作。这就是为什么我们首先有“className”。应用于“多个”事物,而不仅仅是“一个”。
标签: javascript jquery node.js express mongoose