2015-10-07 26 views
2

嘗試使用jQuery將頁面重定向到另一個域。我注意到,如果我嘗試與其他網址重定向,但不會重定向到我想要重定向到的特定網址。也注意到鏈接工作,如果我倒計時之前點擊它,但倒計時爲零時不起作用。這裏是我的HTML和jQuery代碼jquery與倒計時重定向卡在零

<!doctype html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Redirect Site</title> 


    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 


    <!-- Latest compiled and minified JavaScript --> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 


    <script> 
     $(document).ready(function() { 
      var delay = 10 ; 
      var url = "http://www.wordoflifedubuque.org"; 

      function countdown() { 
       setTimeout(countdown, 1000) ; 
       $('#countmesg').html("Redirecting in " + delay + " seconds."); 
       delay --; 
       if (delay < 0) { 
       window.location = url ; 
       delay = 0 ; 
      } 
     } countdown() ; 
    });  


    </script> 

    <style> 
     #countmesg{ 
      font-size: 2em; 
      text-align: center; 
      font-weight: bold; 
     } 


     .header{background-color: black;} 
    </style> 

</head> 

<body> 
<div class="container"> 
    <div class="row"> 
     <div class="col-sm-12 header"> 
      <img src="logo.png" class="res"> 
     </div> 
    </div> 
    <div class="row"> 
      <div class="col-sm-12"> 
       <h3>This website has moved, click the link <a href="http://www.wordoflifedubuque.org">http://wordoflifedubuque.org</a> to go to the new site or be redirected automatically.</h3> 
       <div id="countmesg"></div> 
      </div> 
    </div> 



</div> 

</body> 
</html> 

回答

1

如果你按照你的工作流程,它確實工作。問題是它不停止工作。一旦它達到一個低於0的數字,它就會繼續循環,所以超時從不停止。這可能是造成問題,所以儘量取消超時時重定向:

$(document).ready(function() { 
     var delay = 10 ; 
     var url = "http://www.wordoflifedubuque.org"; 
     var timer=null 
     function countdown() { 
      timer = setTimeout(countdown, 1000) ; 
      $('#countmesg').html("Redirecting in " + delay + " seconds."); 
      delay --; 
      if (delay < 0) { 
       clearTimeout(timer); 
       window.location = url ; 
       delay = 0 ; 
      } 
     } 
     countdown() ; 
});  
+0

謝謝蒂姆。這工作:) – Olucrown

1

您繼續循環的10秒後的,作爲你加載另一個調用countdown在事件循環之前,你檢查delay嘗試後檢查。此外該網站沒有「www」

 function countdown() { 
      $('#countmesg').html("Redirecting in " + delay + " seconds."); 
      delay --; 
      if (delay < 0) { 
      window.location = url ; 
      delay = 0 ; 
      return; // don't wait again 
      } 

      setTimeout(countdown, 1000) ; 
    } countdown() ; 
+0

你的代碼仍然在做和以前一樣的事情,當倒計時爲零時頁面卡住了。 – Olucrown

+0

注意'return'語句,如果延遲低於零,'setTimeout'不能再運行。 – Victory