2013-05-11 111 views
-1

我現在正在研究一段JavaScript代碼,它將用於重定向顯示的計數器頁面。問題是,當計數器達到0時,countDown()函數進入無限循環,導致頁面保持不變。當然,我還無法解決問題。誰能幫忙?JavaScript中的頁面重定向功能的無限循環

你可以看到這裏的問題: http://kibristaodtuvarmis.com/index.html

代碼如下所示:

var time = 10; 
var page = "http://blog.kibristaodtuvarmis.com"; 


function countDown() 
{   
    if (time == 0) 
    { 
    window.location = page; 
    return(0); 
    } 
    else 
    {  
    time--; 
    gett("container").innerHTML = time; 
    } 
} 

function gett(id) 
{ 
    if(document.getElementById) return document.getElementById(id); 
    if(document.all) return document.all.id; 
    if(document.layers) return document.layers.id; 
    if(window.opera) return window.opera.id; 
} 

function init() 
{ 
    if(gett("container")) 
    { 
     setInterval(countDown, 1000); 
     gett("container").innerHTML = time; 
    } 
    else 
    { 
     setTimeout(init, 50); 
    } 
} 

document.onload = init(); 

編輯:

我已經在讀秒()函數和問題做了如下的變化已解決:

var control = false; 
function countDown() 
{ 
    if (time == 0 && control == false) 
    { 
    control = true; 
    window.location = page; 
    return(0); 
    } 
    else if (time > 0) 
    {  
    time--; 
    gett("container").innerHTML = time; 
    } 
    else 
    { 
    return(0); 
    } 
} 
+0

window.onload = init;將是我的第一個改變,location.replace(page);我的第二個也是最後一個重定向到另一個頁面比當前 – mplungjan 2013-05-11 11:46:33

+0

你可能想要'document.all [id]'而不是'document.all.id'或更好,只是除掉'getElementById'之外的所有東西。除非這是一些嚴重的遺留代碼。 – Dennis 2013-05-11 12:15:48

回答

0

通過更換您的完整的JavaScript代碼嘗試這部分代碼爲:

var time = 10; 
    var page = "http://blog.kibristaodtuvarmis.com"; 

    function startCount() { 
     time = time - 1; 
     console.log(time); 
     document.getElementById("container").innerHTML = time; 
     startCounter(); 
    } 

    function startCounter() { 
     if (time !== 0) { 
      setTimeout(function() { 
       startCount(); 
      },1000); 
     } else { 
      location.href = page; 
     } 
    } 
    if (window.addEventListener) { 
    window.addEventListener("load", startCount, false); 
    } else if (el.attachEvent) { 
    window.attachEvent("load", startCount); 
    } 

我試了一下,它的工作原理。 測試後告訴我你的答覆。

+0

是的,你的代碼工作得非常好!謝謝! – 2013-05-11 16:47:28

0

你想讓它停在0嗎?分配的setInterval的變種,然後我們可以使用clearInterval如果0

1

我會做這樣的事情:

var b = false; 
    if (time == 0 && b == false) 
    { 
    b = true; 
    window.location = page; 
    return(0); 
    } 
0

您setIinterval繼續改變了window.location執行前,然後使這個循環,因爲時間是0,應該推出window.location的再次

你應該清除間隔

var IdInterval = setInterval(function() { 
//.... code 
    }, 10000); 

和倒計時無線的第一次執行後第一次== 0則:

clearInterval(IdInterval);