js 倒計時 跳轉


1. setTimeout() 方法用於在指定的毫秒數后調用函數或計算表達式。

setTimeout() 只執行 code 一次。如果要多次調用,請使用 setInterval() 或者讓 code 自身再次調用 setTimeout()。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title>setTimeout</title>  
    </head>  
    <body>  
            <div id='div1'>  </div>  
          
    </body>  
    </html>  
      
    <script type="text/javascript">  
    //設定倒數秒數  
    var t = 10;  
    //顯示倒數秒數  
    function showTime(){  
        t -= 1;  
        document.getElementById('div1').innerHTML= t;  
        if(t==0){  
            location.href='http://www.baidu.com';  
        }  
        //每秒執行一次,showTime()  
        setTimeout("showTime()",1000);  
    }  
      
      
    //執行showTime()  
    showTime();  
    </script>  

 

2.

setInterval() 方法可按照指定的周期(以毫秒計)來調用函數或計算表達式。

setInterval() 方法會不停地調用函數,直到 clearInterval() 被調用或窗口被關閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數。

<html>
<body>

<input type="text" id="clock" size="35" />
<script language=javascript>
var int=self.setInterval("clock()",50)
function clock()
  {
  var t=new Date()
  document.getElementById("clock").value=t
  }
</script>
</form>
<button onclick="int=window.clearInterval(int)">
Stop interval</button>

</body>
</html>

 

example :

    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>js定時跳轉頁面的方法</title> 
    </head> 
    <body> 
    <script type="text/javascript"> 
    var t=10;//設定跳轉的時間 
    setInterval("refer()",1000); //啟動1秒定時 
    function refer(){  
        if(t==0){ 
            location="www.baidu.com"; //#設定跳轉的鏈接地址 
        } 
        document.getElementById('show').innerHTML=""+t+"秒后跳轉"; // 顯示倒計時 
        t--; // 計數器遞減 
    } 
    </script> 
    <span id="show"></span> 
    </body> 
    </html> 

 

遇到的問題:

 當將上述js 的方法 放在$(function(){......})中時, 瀏覽器會報 methodXX() is not defined;

應當將function(){}的定義放在 <script></script>中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM