我有一个记录列表,每行上都有一个红叉,以删除该记录。删除可以,但是我发现确认模态中出现一些不必要的行为
[当我单击红叉以删除记录ID 1时,我改变了主意,因此我单击了取消按钮。但是,当我要删除记录2并单击“确认”按钮时,记录1和2均被删除,但我只想删除记录2。
任何想法如何防止我在模态中的取消按钮上的确认按钮之前单击之前删除2条记录?
$(document).on("click", ".delete_item", function(e) {
e.preventDefault();
var user_id = $(this).attr('data-user_id');
var text_modal = "Are you sure?";
$('.modal-body').text(text_modal);
$('#modal-delete').modal('show');
$('.confirmation').on('click', function() {
$.ajax({
type: 'GET',
url: 'delete.php',
data: {
'user_id': user_id
},
success: function(html) { // Removing entire row
$('.ui-sortable li[data-itemid="' + user_id + '"]').remove();
location.reload();
}
});
});
$('.cancellation').on('click', function() {
// Something to prevent double deleting
});
});
问题是因为您要嵌套事件处理程序。这意味着,尽管您取消了第一次删除的模式,但事件仍然绑定到该模式。因此,下次您删除一行时,所有先前打开的模态也会删除它们的相关行。
要解决此问题,请使用单个委托事件处理程序。您可以使用data
属性将它们与行相关联,如下所示:
$(document).on("click", ".delete_item", function(e) {
e.preventDefault();
var user_id = $(this).data('user_id');
$('.confirmation, .cancellation').data('user_id', user_id);
$('.modal-body').text("Are you sure?");
$('#modal-delete').modal('show');
});
$(document).on("click", '.confirmation', function() {
let user_id = $(this).data('user_id');
$.ajax({
type: 'GET',
url: 'delete.php',
data: { user_id: user_id },
success: function(html) { // Removing entire row
$('.ui-sortable li[data-itemid="' + user_id + '"]').remove();
location.reload();
}
});
});
$(document).on("click", '.cancellation', function() {
let user_id = $(this).data('user_id');
// do something...
});
这里还有几件事要注意。首先使用data()
来获取/设置data
属性,而不是attr()
。其次,对delete.php
的调用使用DELETE HTTP动词会更有意义。