在进行web前端开发实战练习时,我们常常遇到一种问题就是,web前端开发应该如何实现页面N秒之后自动跳转呢?通过查找相关html教程,总结了3个方法:

方法1:

最简单的一种:直接在前面<head>里面添加代码:

1. <span style="font-size:18px;">   </span><span style="font-size:24px;"><meta http-equiv="refresh" content="3;URL=res.html"> </span>  

1. <span style="font-size:24px;">//3秒之后自动跳转到res.html,两个属于同一文件下面,要是需要跳转到jsp页面,就需要在url里面填写url地址————(浏览器的地址栏里面写入的数据,如:http://localhost:8080/TestDemo/1.jsp)</span>  

方法2:

需要用到window里面的方法: 

setTimeout:经过指定毫秒值后计算一个表达式。

例子:

1. window.setTimeout("alert('Hello, world')", 1000);  

这个是写在js代码里面的;

具体实现如下:

1. <script type="text/javascript">  

2.         onload=function(){     <span style="white-space:pre">             </span>//在进入网页的时候加载该方法  

3.             setTimeout(go, 3000); <span style="white-space:pre">  </span> /*在js中是ms的单位*/  

4.         };  

5.         function go(){  

6.             location.href="http://localhost:8080/TestDemo/index.jsp";   

7.         }  

8. </script>  

1. //3秒之后自动执行go方法,直接跳转到index.jsp页面  

方法3:

上面两个例子的缺陷就是能够实现跳转,但是不知道是什么时候跳转.实现倒数3-2-1;

 settimeout:方法已经做不了了;

setInterval:每经过指定毫秒值后计算一个表达式。
没过相同的时间,就会执行相应的函数。具体的实现方法:

1. <script type="text/javascript">  

2.     onload=function(){  

3.         setInterval(go, 1000);  

4.     };  

5.     var x=3; //利用了全局变量来执行  

6.     function go(){  

7.     x--;  

8.         if(x>0){  

9.         document.getElementById("sp").innerHTML=x;  //每次设置的x的值都不一样了。  

10.         }else{  

11.         location.href='res.html';  

12.         }  

13.     }  

14. </script>  

setTimeout