我是 Javascript / jQuery 新手。我想使用“sweetalert”库显示一些警报消息,并且根据用户响应,该函数将返回或继续。
这是我的实现:
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
jQuery.getScript('https://unpkg.com/sweetalert/dist/sweetalert.min.js', function() {
swal({
title: "Do you want Continue ? ",
text: "You need to pay extra amount",
icon: "success",
buttons: true,
confirmButtonColor: '#C64EB2',
})
.then((willSubmit) => {
if (!willSubmit) {
return false;
}
});
});
// rest of the code
});
这里的期望是,如果用户选择“取消”按钮,该函数应返回 false,否则在选择“确定”按钮时,将执行“其余代码”部分。
但这里的问题是代码不会因用户输入而停止而是继续。显示警报框,但忽略用户选择。
我知道实施是错误的,但不确定正确的方法是什么。
谢谢!!
你需要使用Swal.fire();让它发挥作用。
https://sweetalert2.github.io/
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
e.preventDefault();
jQuery.getScript('https://cdn.jsdelivr.net/npm/sweetalert2@11', function() {
Swal.fire({
title: 'Do you want Continue ?',
text: "You need to pay extra amount",
icon: 'success',
showCancelButton: true,
confirmButtonColor: '#C64EB2',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Confirmed!',
'You agreed to pay extra amount.',
'success'
)
} else {
console.log('clicked cancel');
}
})
})
// rest of the code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="some_exchnage_request_form">
<input type="submit">
</form>
有类似的问题,看起来这是“sweetalert”的限制,与js中的alert()/confirm()不同,执行不会因用户输入而停止。