Nea*_*eal 41
$('body').bind('beforeunload',function(){
//do something
});
Run Code Online (Sandbox Code Playgroud)
但是这不会保存以后的任何信息,除非您计划将其保存在某个地方的cookie(或本地存储)中,并且unload事件并不总是在所有浏览器中触发.
示例:http: //jsfiddle.net/maniator/qpK7Y/
码:
$(window).bind('beforeunload',function(){
//save info somewhere
return 'are you sure you want to leave?';
});
Run Code Online (Sandbox Code Playgroud)
Uza*_*air 16
如果你想在页面刷新之前预订一些变量
$(window).on('beforeunload', function(){
// your logic here
});
Run Code Online (Sandbox Code Playgroud)
如果你想在某些条件下加载一些内容
$(window).on('load', function(){
// your logic here`enter code here`
});
Run Code Online (Sandbox Code Playgroud)
所有的代码都是客户端的,我希望你这很好用这个:
首先,我们将使用3个函数:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
Run Code Online (Sandbox Code Playgroud)
现在我们将从页面加载开始:
$(window).load(function () {
//if IsRefresh cookie exists
var IsRefresh = getCookie("IsRefresh");
if (IsRefresh != null && IsRefresh != "") {
//cookie exists then you refreshed this page(F5, reload button or right click and reload)
//SOME CODE
DeleteCookie("IsRefresh");
}
else {
//cookie doesnt exists then you landed on this page
//SOME CODE
setCookie("IsRefresh", "true", 1);
}
})
Run Code Online (Sandbox Code Playgroud)