2013-11-20 59 views
4
window.onbeforeunload = function(evt) { 
    var message = 'Are you sure you want to leave the page. All data will be lost!'; 

    if (typeof evt === 'undefined') { 
     evt = window.event; 
    } 
    if (evt && !($("#a_exit").click)) { 
     evt.returnValue = message; 
    } 
    return message; 
}; 

我希望用戶離開頁面點擊鏈接(僅有id ="a_exit")。在其他情況下,例如刷新頁面,點擊另一個鏈接,將提示用戶如果他/她想離開頁面。我試圖使用上面的代碼。當我點擊退出鏈接時,它仍然問我是否想離開。在頁面上有條件的onbeforeunload事件

回答

2

您可以刪除點擊處理程序中的window.onbeforeunload

+1

我猜測它不會工作,但在最後一個鉻,IE和FF下測試,它的工作原理http://jsfiddle.net/Suf99/ –

0

如果鏈接被點擊,變量如何決定?

var exitClicked = false; 

$("#a_exit").click(function() { 
    exitClicked = true; 
}); 

window.onbeforeunload = function(evt) { 
    //... 

    if(evt && !exitClicked) { 
    evt.returnValue = message; 
    } 

    //... 
}; 

只設置了當鏈路真的點擊事後,卸載你可以簡單地檢查這個變量之前。

+0

對不起,它沒有任何變化 – zkanoca

3
$(window).bind('beforeunload',function() { 
    return "'Are you sure you want to leave the page. All data will be lost!"; 
}); 

$('#a_exit').live('click',function() { 
    $(window).unbind('beforeunload'); 
}); 

上述工作對我來說

+0

這工作正常。謝謝。 –

1

我的條件提示的簡單的例子離開頁面之前:

window.onbeforeunload = confirmExit; 
    function confirmExit(event) { 
     var messageText = tinymce.get('mMessageBody').getContent(); 
     messageText = messageText.trim(); 

     // ... whatever you want 

     if (messageText != "") 
      return true; 
     else 
      return void (0); 
    }; 

它的工作原理鉻,FF下。

+0

非常感謝。它在IE9和Safari瀏覽器中也可以正常工作。發送自定義消息而不是在舊瀏覽器中返回true,在樂趣返回時使用下面的行。 'return _isSaved? void(0):「你在這個窗口上有未保存的工作。」 –

相關問題