beforeunload事件在當頁面卸載(關閉)或刷新時調用,事件觸發的時候彈出一個有確定和取消的對話框,確定則離開頁面,取消則繼續待在本頁;
jquery離開頁面彈出提示代碼
//綁定beforeunload事件
$(window).bind(
'beforeunload'
,
function
(){
return
'您輸入的內容尚未保存,確定離開此頁面嗎?'
;
});
//解除綁定,一般放在提交觸發事件中
$(window).unbind(
'beforeunload'
);
js離開頁面提示 onbeforeunload事件方法
window.onbeforeunload =
function
(event) {
return
confirm(
"確定退出嗎"
);
}
以下操作觸發beforeunload,onbeforeunload
1 ·關閉瀏覽器窗口
2·通過地址欄或收藏夾前往其他頁面的時候
3·點擊返回,前進,刷新,主頁其中一個的時候
4·點擊 一個前往其他頁面的url連接的時候
5·調用以下任意一個事件的時候:click,document.write()方法(輸出內容),document.open() 打開一個新的空白文檔,document.close()方法可關閉一個由open()方法打開的輸出流,並顯示選定的數據。
,window close (),form.submit.
,window close (),form.submit.
6·當用window open打開一個頁面,並把本頁的window的名字傳給要打開的頁面的時候。
7·重新賦予location.href的值的時候。
8·通過input type=”submit”按鈕提交一個具有指定action的表單的時候。
9.可以用在以下元素:
body, frameset, window
// 關閉窗口時彈出確認提示
$(window).bind('beforeunload', function(){
// 只有在標識變量is_confirm不為false時,才彈出確認提示
if(window.is_confirm !== false){
return '您可能有數據沒有保存';
}
});
// 提交表單時,不彈出確認提示框
$('form').bind('submit', function(){
is_confirm = true;
});
//頁面內的跳轉操作均不彈出確認窗口
$(window).bind('mouseover mouseleave', function(event){
is_confirm = event.type == 'mouseleave';
});
(function(){
// 關閉窗口時彈出確認提示
$(window).bind('beforeunload', function(){
// 只有在標識變量is_confirm不為false時,才彈出確認提示
if(window.is_confirm !== false)
return '您可能有數據沒有保存';
})
// mouseleave mouseover事件也可以注冊在body、外層容器等元素上
.bind('mouseover mouseleave', function(event){
is_confirm = event.type == 'mouseleave';
});
})();
<script type="text/javascript">
var changeFlag=false;
//標識文本框值是否改變,為true,標識已變
$(document).ready(function(){
//文本框值改變即觸發
$("input[type='text']").change(function(){
changeFlag=true;
});
//文本域改變即觸發
$("textarea").change(function(){
changeFlag=true;
});
});
//離開頁面時保存文檔
window.onbeforeunload = function() {
if(changeFlag ==true){
//如果changeFlag的值為true則提示
if(confirm("頁面值已經修改,是否要保存?")){
//處理信息保存...
alert("即將執行保存操作...");
}else{
//不保存數據...
alert("不保存信息...");
}
}
var changeFlag=false;
//標識文本框值是否改變,為true,標識已變
$(document).ready(function(){
//文本框值改變即觸發
$("input[type='text']").change(function(){
changeFlag=true;
});
//文本域改變即觸發
$("textarea").change(function(){
changeFlag=true;
});
});
//離開頁面時保存文檔
window.onbeforeunload = function() {
if(changeFlag ==true){
//如果changeFlag的值為true則提示
if(confirm("頁面值已經修改,是否要保存?")){
//處理信息保存...
alert("即將執行保存操作...");
}else{
//不保存數據...
alert("不保存信息...");
}
}