Winar_阿进
2016-01-14 23:42
<!DOCTYPE html>
<html>
<head>
<title>浏览器对象</title>
<meta http-equiv="Content-Type" content="text/html; charset=gkb"/>
</head>
<body>
<!--先编写好网页布局-->
<h3>操作成功</h3>
<p><b id="second">5</b>秒后返回到主页 <br></p>
<a href="javascript:goBack();">返回(第一种方法)</a><br><br>
<a href="" onclick="window.history.go(-1)">返回(第二种方法)</a>
<script type="text/javascript">
var sec = document.getElementById("second");
var i=5;
var Timer = setInterval("timer()",1000);
function timer()
{
i--;
sec.innerHTML = i;
if(i==1)
{
window.location.href = "http://www.imooc.com/learn/10";
}
}
function goBack()
{
window.history.go(-1);
}
//获取显示秒数的元素,通过定时器来更改秒数。
//通过window的location和history对象来控制网页的跳转。
</script>
</body>
</html>谢谢!
你这个不是到-2秒才跳转,而是到1秒的时候已经跳转了,你看到的到-2秒是你跳转打开网页需要时间给你的错觉,根本原因是你没有设置计时器停止,即使到了1秒的时候还是会不停执行timer()函数,你要在跳转语句下面添加一句清除计时器语句clearInterval(Timer);这样到了1秒的时候就不会继续减少时间了
改if(i==0)
JavaScript进阶篇
469057 学习 · 22582 问题
相似问题