2014-09-22 73 views
0

我希望当用户离开我的网站(不仅仅是网页,整个网站)时,应该给用户一个弹出窗口。当用户离开我的网站时显示弹出窗口

我已经实现了一种方法,但每次浏览网页时都会弹出。

window.onbeforeunload = function (evt) { 


    var message = 'Are you sure you want to navigate away from myWEbSite?'; 
    if (typeof evt == 'undefined') { 
    evt = window.event; 

    } 
    if (evt) { 
    evt.returnValue = message; 
    } 

    return message; 

} 

回答

0

您可以玷污自己的jQuery选择,像这样:

$.expr[':'].external = function(obj){ 
    return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname); 
}; 
$.expr[':'].internal = function(obj){ 
    return obj.hostname == location.hostname; 
}; 

然后你就可以做到以下几点:

$(function() { 
    var unloadMessage = function() { 
     return "Are you sure you want to navigate away from myWEbSite?"; 
    }; 

    $('a:internal').click(function() { 
     window.onbeforeunload = null; 
    }); 
    $('form').submit(function() { 
     window.onbeforeunload = null; 
    }); 

    $('a:external').click(function() { 
     window.onbeforeunload = unloadMessage; 
    }); 

    window.onbeforeunload = unloadMessage; 
}); 

在特定情况下,你只需要设置window.onbeforeunload == null每当导航点击链接或提交内部表单。

相关问题