目前,我有一个函数,当更改下拉列表中的值时,它会请求用户确认。使用标准的JavaScript confirm()可以很好地工作。这是小提琴。
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函数返回不起作用。
然而,在谷歌搜索后,我发现一些人也有类似的问题。
但是这似乎有点麻烦,因为它阻止了任何操作,但是在选择“确认”时,他会重新创建默认情况下应该调用的函数。对于如此简单的事情来说,这似乎是一个相当大的黑客。
SweetAlert是否有可能就像一个普通的confirm对话框?
发布于 2016-05-27 11:27:12
该值不会被设置,因为this在swal中不是select,而是甜警报对话框。因此,在您的change事件中,您必须定义一个保存已更改的select元素的变量,并在用户单击“No”时使用它来设置值。
.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;
}
});
});您可以在这个小提琴中找到一个有用的示例。
发布于 2016-05-27 11:28:37
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;
}
});
});
https://stackoverflow.com/questions/37481157
复制相似问题