如何使用甜蜜警报确认?

在这个代码表格提交,即使我点击否

document.querySelector('#from1').onsubmit = function(){ swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, I am sure!', cancelButtonText: "No, cancel it!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm){ swal("Shortlisted!", "Candidates are successfully shortlisted!", "success"); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); } }); }; 

您需要在提交时阻止默认表单行为。 之后,如果选择了“确定”按钮,则需要以编程方式提交表单。

这是它的样子:

 document.querySelector('#from1').addEventListener('submit', function(e) { var form = this; e.preventDefault(); // <--- prevent form from submitting swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", icon: "warning", buttons: [ 'No, cancel it!', 'Yes, I am sure!' ], dangerMode: true, }).then(function(isConfirm) { if (isConfirm) { swal({ title: 'Shortlisted!', text: 'Candidates are successfully shortlisted!', icon: 'success' }).then(function() { form.submit(); // <--- submit form programmatically }); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); } }) }); 

UPD。 上面的示例使用sweetalert v2.x promise API。

演示: http //plnkr.co/edit/YTY7PDs5Uh1XGUo9ic1s?p=preview

你需要使用then()函数,就像这样

 swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, I am sure!', cancelButtonText: "No, cancel it!" }).then( function () { /*Your Code Here*/ }, function () { return false; }); 
 document.querySelector('#from1').onsubmit = function(e){ swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, I am sure!', cancelButtonText: "No, cancel it!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm){ swal("Shortlisted!", "Candidates are successfully shortlisted!", "success"); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); e.preventDefault(); } }); }; 
 swal({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Confirm!' }).then(function(){ alert("The confirm button was clicked"); }).catch(function(reason){ alert("The alert was dismissed by the user: "+reason); });