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

时间:2014-09-09 16:48:53

标签: javascript jquery

访问者想要离开页面(重新加载,刷新,关闭标签等等),然后触发一个功能,提示模式“你确定要离开吗?”。

如果他们点击链接,我想允许他们离开没有模态提示的页面。

这是一个jsfiddle示例 - http://jsfiddle.net/vvj90z8h/3/

<a href="http://www.google.com" class="button">Proceed</a>      
<div class="price">$139.99</div>

// 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();
}

如果刷新页面,模态会显示,这没关系。

我想点击链接而没有模态显示。

3 个答案:

答案 0 :(得分:1)

您可以在点击时取消绑定onbeforeunload事件侦听器:

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

Demonstration

答案 1 :(得分:0)

点击或取消绑定事件时设置标记

(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?';
    });

}());

答案 2 :(得分:0)

http://jsfiddle.net/jcqjj1u3/2/

// 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');
});