[英]How to immediately redirect using JavaScript
如何讓 javascript立即停止腳本執行並切換到另一個頁面。 考慮一下:
<html>
<head>
<script>
function onload()
{
alert('before');
window.location.href = 'http://google.com';
alert('after redirect');
}
</script>
</head>
<body onload="onload();">
Hello World!
</body>
</html>
第二條警報消息總是會觸發。
嘗試從第一個函數返回值,如果用戶登錄則返回 true。 我希望這會幫助你。
function init() {
if(checkIfLoggedIn()) {
getUserInfo(); // I would expect this to not run if the user was not logged in
}
}
function checkIfLoggedIn() {
if(loggedIn() === false) {
window.location.href = "/login.html";
} else {
return true;
}
}
function getUserInfo() {
var username = getUsername(); // throws exception if not logged in
var email = getEmail(); // throws exception if not logged in
// etc. etc.
}
您在調用getUserInfo()
時沒有任何條件。 所以這個函數會在頁面加載時被調用,因為你沒有對這個函數調用設置限制。 因此,代碼仍在運行。
也許這就是您的代碼段的第一個塊中的意圖:
if(checkIfLoggedIn()) {
getUserInfo();
}
這樣一來, getUserInfo
將僅稱為checkIfLoggedIn
返回true
。 按照您編寫的方式,當頁面加載時getUserInfo
也在運行。
如果你不想亂扔你的代碼,你可以打破所有規則並使用例外:
function init() { checkIfLoggedIn(); getUserInfo(); // I would expect this to not run if the user was not logged in } function checkIfLoggedIn() { if(loggedIn() === false) { window.location.href = "/login.html"; throw new Error('Kill all code running after me'); } } function getUserInfo() { var username = getUsername(); // throws exception if not logged in var email = getEmail(); // throws exception if not logged in // etc. etc. } function loggedIn() { return false; } init();
拋出的異常將阻止執行所有其余代碼。
好的。 它很丑陋,而且違反了許多最佳實踐規則。 但它應該工作。
或者您可以在其他代碼周圍使用異常處理:
function init() { checkIfLoggedIn(); getUserInfo(); // I would expect this to not run if the user was not logged in } function checkIfLoggedIn() { if(loggedIn() === false) window.location.href = "/login.html"; } function getUserInfo() { try { var username = getUsername(); var email = getEmail(); // etc. etc. } catch(ex) { // Don't do anything here unless you really need to } } function loggedIn() { return false; } init();
我今天在尋找其他東西時遇到了答案:
即使設置了window.location.href
並且窗口處於重定向過程中,代碼在大多數瀏覽器中仍會繼續執行:
function onload()
{
console.log('before');
window.location.href = 'newpage.html';
console.log('after redirect 1');
console.log('after redirect 2');
console.log('after redirect 3');
}
after redirect 1
after redirect 2
, after redirect 2
, after redirect 3
,即使頁面正在被重定向,仍然會登錄到控制台。 但是,由於init()
是頂級函數,我可以return;
從函數並停止代碼繼續執行..
<script>
function init()
{
if(checkIfLoggedIn() === false)
return; // <-- stops following code from executing and allows return to proceed
getUserInfo();
}
function checkIfLoggedIn()
{
var loggedIn = loggedIn();
if(loggedIn === false)
window.location.href = "/login.html";
return loggedIn;
}
...
</script>
</head>
<body onload="init()">
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.