我目前有一个功能,要求用户在更改下拉列表中的值时进行确认。这可以使用标准JavaScript
confirm()
正常工作。这是fiddle。
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function () {
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Proceed as normal.
} else {
// Reset the value & stop normal event
$(this).val(prev_val);
return false;
}
});
但是当使用SweetAlert
时,更改事件总是在我能够确认/取消之前发生。这意味着,当我选择一个新值并按“取消”时,它不会停止该事件并重置之前的值。它与常规JavaScript
confirm
对话框有关。
var prev_val;
$('#' + dropdownId).focus(function () {
prev_val = $(this).val();
}).change(function (e) {
$(this).blur();
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
return true;
} else {
$(this).val(prev_val);
return false;
}
});
});
值得注意的是,此JavaScript
可能无效(JavaScript
的新内容),例如:从confirm
函数和swal
函数返回不起作用。
然而,谷歌搜索后,我发现有类似问题的人。
但是这似乎有点hacky,因为它阻止了任何操作,但是当选择确认时,他重新创建应该默认调用的函数。对于这么简单的事情来说,这似乎很糟糕。
SweetAlert
是否有可能像常规confirm
对话一样?
答案 0 :(得分:4)
由于this
中的swal
不是选择,而是甜蜜警报对话框,因此不会设置该值。因此,在您的更改事件中,您必须定义一个包含已更改的select元素的变量,并在用户单击“否”时使用它来设置值。
.change(function(e) {
var select = this; // save select element to variable
$(this).blur();
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
e.preventDefault();
return true;
} else {
$(select).val(prev_val); // use select reference to reset value
return false;
}
});
});
您可以在此fiddle找到一个有效的例子。
答案 1 :(得分:1)
var prev_val;
$('#' + dropdownId).focus(function() {
prev_val = $(this).val();
}).change(function(e) {
$(this).blur();
var self = this;
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
// preventDefault is useless since change event has already happened
// if Confirm is true then do nothing else
// change with prev val
//e.preventDefault();
return true;
} else {
// this here does not refer the dom element
// it might be changed because it is called through the swal library code at a later time, use self which is declared out of the callback context.
$(self).val(prev_val);
return false;
}
});
});