如何创建一个等待用户确认他是否真的要删除数据的JQuery函数。
我怎样才能实现这样的目标:
function UserConfirmation()
{
ShowModal(); //"Global" Delete Confirmation Bootstrap Modal
//Now wait till the user decides whether or not he really wants to
//delete data(Button events or on Modal hide).
//On user reply:
if(UserReplied == 'Delete')
{}
else
{}
}
修改
这是布局中Modal的html代码。只要需要,就可以通过ShowModal()函数调用此ModalDelete。
<!-- Delete Data Confirmation Modal -->
<div class="modal fade" id="ModalDelete" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" id="btn-cancel" data-dismiss="modal">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btn-cancel" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger btn-delete" id="btn-delete" data-dismiss="modal">Delete</button>
</div>
</div>
</div>
</div>
函数UserConfirmation在调用ShowModal()之后侦听Modal事件,按下按钮或模态隐藏将根据用户的选择继续进行。
我认为这可以通过承诺或违背行动来实现。
答案 0 :(得分:1)
好的,我在这里解决了使用Jquery deferred的承诺的问题:
此函数侦听,直到用户点击#ModalDelete中的按钮并返回点击按钮的ID。
function ModalOptionChoosen() {
var deferred = $.Deferred();
$('#ModalDelete button').on('click', function (e) {
var $target = $(e.target); // Clicked button element
$(this).closest('.modal').on('hidden.bs.modal', function () {
//console.log($target); // Logged if the clicked button actually closed the modal
var result = $target.attr('id');
deferred.resolve(result);
});
});
return deferred.promise();
};
当另一个函数等待返回ModalOptionChoosen()以上的承诺时。
function ShowModalWaitForResult () {
ShowModal();
var promise = ModalOptionChoosen();
promise.done(function (result) {
console.log(result); // log the user selected value
});
});
现在我可以在任何地方引用ModalOptionChoosen函数。
答案 1 :(得分:0)
例如,您可以使用http://nakupanda.github.io/bootstrap3-dialog,然后在需要删除确认时使用类似的内容:
BootstrapDialog.show({
title: 'Alert',
message: 'Are you sure you want to delete this ?',
buttons: [{
label: 'Yes',
cssClass: 'btn-danger',
action: function(dialog) {
dialog.close();
//your action
}
}, {
label: 'No',
action: function(dialog) {
dialog.close();
}
}]
});`