sweetalert 立即消失

sweetalert disappear Instantly

swal({
    title: "xxx",
    type: "warning",
    showCancelButton: true,
    .....
    },
    function(isConfirm) {
        if (isConfirm) {
            swal("yes, do it!");
        } else {
            swal("cannel!");
        }
    }
);

在我的页面中一个按钮绑定了一个js函数,该函数执行这段代码。当我点击按钮时,页面上出现 "are you sure" 确认框。但是当我点击 yes 时,下一个 sweetalert 就会刷新并立即消失。怎么了?

貌似插件的关闭操作是用定时器做一些清理,300ms后执行,所以新的alert也正在清理。

修复它的一个技巧是使用像

这样的计时器

swal({
    title: "xxx",
    type: "warning",
    showCancelButton: true
  },
  function(isConfirm) {
    debugger;
    setTimeout(function() {
      if (isConfirm) {
        swal("yes, do it!");
      } else {
        swal("cannel!");
      }
    }, 400)
  }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet" />

既然问题已经解决了,那就换个方法吧。

您也可以使用 event.preventDefault() 作为第 2 个 sweetalert。我遇到了同样的情况,只是我只有 1 个 sweetalert 可以显示。

来自 this mozilla page

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

点击提交按钮后,它出现了一个实例,然后我被定向到另一个页面(在 action 属性中指定)。由于这是默认情况下发生的,因此使用 event.preventDefault() 使其保留下来。

感谢分享您的疑惑!

将 closeonconfirm 属性设置为 false 即 closeOnConfirm: false,

一旦您调用显示甜蜜警报的函数,请确保调用按钮类型应保持为按钮不提交。

<form  method="post">                                 
 <button  type="button" class="btn-wide btn btn-info" onclick="buy_harvest()">Buy</button>
                                            <button  type="submit" class="btn-wide btn-shadow btn btn-success" name="good_condition">Good condition</button>
                                            <button  type="submit" class="btn-wide btn btn-danger" name="inedible">Inedible</button>                                              </form>  

<script>
    function buy_harvest(){
       

    var { value: formValues } = Swal.fire({
        title: 'How mutch want to Buy?',
        showCancelButton: true,
        confirmButtonText: `Buy`,
        html:
          '<div style="float:left;"><input type="text" id="buy_qty" style="width:150px;"><label> Quanity </label></div>' ,
          
        focusConfirm: false,
        preConfirm: () => {
          var buy_qty = document.getElementById("buy_qty").value;
          if(buy_qty!="" || buy_qty!=0){
           
            //call to another function and pass value
            process_buy(buy_qty);
          }       
        }
      })
    }
</script> 

只需在 swal 函数前添加 event.preventDefault(); 即可防止其消失。