首页 > 解决方案 > 在用户确认之前如何防止页面卸载?

问题描述

我有弹出窗口出现,但页面继续卸载。.js-close在单击或提交弹出窗口中的表单之前,如何防止页面卸载?

$(document).ready(() => {
    window.onbeforeunload = () => {
        const newsSubscribePopup = $('#news-subscribe-popup');

        if (newsSubscribePopup.length) {
            $.magnificPopup.open({
                items: {
                    src: newsSubscribePopup,
                },
                type: 'inline',
                preloader: true,
                modal: true,
                showCloseBtn: false,
            });
        }
    };
});`

标签: javascriptjqueryonbeforeunloadmagnific-popup

解决方案


您可以将 confirm() 函数与 onclick 处理程序一起使用。
下面是一个简单的例子:

<div class="js-close" data-confirm="Are you sure to delete this item?">action</div>

$('.js-close').on( "click", function() {

      var choice = confirm($(this).attr("data-confirm"));

      if (choice) {
        alert('ok');
      }else{
        alert('no');
      }

});

http://jsfiddle.net/spbjqvgw/


推荐阅读