JavaScript实现时间倒计时跳转(推荐)
1.setTimeout()方法用于在指定的毫秒数后调用函数或计算表达式。
setTimeout()只执行code一次。如果要多次调用,请使用setInterval()或者让code自身再次调用setTimeout()。
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>setTimeout</title>
</head>
<body>
<divid='div1'></div>
</body>
</html>
<scripttype="text/javascript">
//设定倒数秒数
vart=10;
//显示倒数秒数
functionshowTime(){
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>
<inputtype="text"id="clock"size="35"/>
<scriptlanguage=javascript>
varint=self.setInterval("clock()",50)
functionclock()
{
vart=newDate()
document.getElementById("clock").value=t
}
</script>
</form>
<buttononclick="int=window.clearInterval(int)">
Stopinterval</button>
</body>
</html>
下面给大家介绍下相关阅读
1.setInterval()函数可以参阅setInterval()函数用法详解一章节。
2.location.href可以参阅Location对象的href属性一章节。
3.innerHTML属性可以参阅js的innerHTML属性的用法一章节。
下面通过示例(example)给大家介绍下:
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>js定时跳转页面的方法</title>
</head>
<body>
<scripttype="text/javascript">
vart=10;//设定跳转的时间
setInterval("refer()",1000);//启动1秒定时
functionrefer(){
if(t==0){
location="www.baidu.com";//#设定跳转的链接地址
}
document.getElementById('show').innerHTML=""+t+"秒后跳转";//显示倒计时
t--;//计数器递减
}
</script>
<spanid="show"></span>
</body>
</html>
遇到的问题:
当将上述js的方法放在$(function(){......})中时,浏览器会报methodXX()isnotdefined;
应当将function(){}的定义放在<script></script>中
以上所述是小编给大家介绍的JavaScript实现时间倒计时跳转(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!