在我的網站我在新窗口中進行考試&我希望如果用戶關閉此窗口,他將被重定向到其他頁面,如果他按下'ok'確認。但如果按下「取消」,他應該呆在那裏。我正在使用的JavaScript是以下。即使點擊確認框中的'取消'按鈕,窗口關閉
/**
* This javascript file checks for the brower/browser tab action.
* It is based on the file menstioned by Daniel Melo.
* Refer: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
*/
var validNavigation = false;
function endSession() {
$choice = confirm("You will exit your CSA test. Are you sure you want to close the window?");
if ($choice)
window.open('Result.aspx', '_blank', 'toolbar=0, scrollbars=1');
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function (e) {
if (e.keyCode == 116) {
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
wireUpEvents();
});
這裏就點擊「確定」按鈕的「Result.aspx」窗口打開成功,但這裏的問題是,如果用戶點擊確認框,然後也窗口被關閉,得到「取消」。 請告訴我我該錯在哪裏或者有其他選擇。 任何形式的幫助將不勝感激。 在此先感謝!
您必須從'window.onbeforeunload'返回一個字符串,它將從您無法控制的瀏覽器中打開一個確認框。如果用戶按下取消,導航將被中斷。欲瞭解更多信息,請參閱[這個問題](http://stackoverflow.com/questions/12570800/onbeforeunload-and-onunload-getting-one-to-work-after-the-other/12570865#12570865) – jbabey 2013-04-23 19:37:45