Javascript 如果页面刷新,则显示模式,但如果遵循链接则不显示模式

Javascript 如果页面刷新,则显示模式,但如果遵循链接则不显示模式,javascript,jquery,Javascript,Jquery,访问者想要离开页面(重新加载、刷新、关闭选项卡等),然后会触发一个函数,提示一个模式“您确定要离开吗?” 我想允许他们在点击链接时离开页面而不显示模式提示 下面是一个JSFIDLE示例- $139.99 //作用 priceFunction=函数(){ window.onbeforeunload=函数(){ 返回“确定要离开吗?”; } }; //如果价格为139.99,则运行函数 var price=$(“.price”).text().replace(/[^0-9\.]/g'); 如果(价

访问者想要离开页面(重新加载、刷新、关闭选项卡等),然后会触发一个函数,提示一个模式“您确定要离开吗?”

我想允许他们在点击链接时离开页面而不显示模式提示

下面是一个JSFIDLE示例-


$139.99
//作用
priceFunction=函数(){
window.onbeforeunload=函数(){
返回“确定要离开吗?”;
}
};
//如果价格为139.99,则运行函数
var price=$(“.price”).text().replace(/[^0-9\.]/g');
如果(价格=139.99){
priceFunction();
}
如果刷新页面,模式会显示,这是正常的


我想单击链接,而不是模式显示。

您可以在卸载之前解除
事件侦听器的绑定,单击:

$('#proceed').click(function(){ window.onbeforeunload = null; });

当他们单击或解除绑定事件时设置标志

(function(){
    var pass = false;
    $(document.body).on("mousedown","a.button", function () {
        pass = true;
    });

    window.onbeforeunload = function() {
        if(pass) return;
        return 'Sure you want to leave?';
    }

}());


您希望它不提示的依据是什么?也许将“不提示”作为默认操作,“提示”作为显式操作会更容易些?这与问题完全相同。@EhsanSajjad不显示的依据是该链接是否正确clicked@David我尝试过这个方法,但第一个条件是url是否包含“shoppingcart”。我想这让我很扫兴,所以我一开始就错过了你建议的路线。不过谢谢你的建议,我还是可以试试:)非常感谢svassr!我首先看到了Dystroys的答案,但这也非常有效
(function(){
    var pass = false;
    $(document.body).on("mousedown","a.button", function () {
        pass = true;
    });

    window.onbeforeunload = function() {
        if(pass) return;
        return 'Sure you want to leave?';
    }

}());
(function(){

    $(document.body).on("mousedown","a.button", function () {
        $(window).off("beforeunload");    
    });

    $(window).on("beforeunload", function() {
        return 'Sure you want to leave?';
    });

}());
// function
priceFunction = function (){
    window.onbeforeunload = function() {
            return 'Sure you want to leave?';
    }
};

// if price is 139.99, run function
var price = $(".price").text().replace(/[^0-9\.]/g, '');
if (price = 139.99){
    priceFunction();
}

var beforeUnloadFunction;

$('.button').click(function(){
    beforeUnloadFunction = window.onbeforeunload; // save the function for later just in case
    window.onbeforeunload = null;
    // following code is optional. Use it only if you need to do other stuff befre leaving
    event.preventDefault();
    // do other stuff before leaving if you'd like to
    location.href= $(this).attr('href');
});