2011-08-06 55 views
9

HTML结构:等待两秒钟然后自动重定向jquery中的另一个页面?

<div class="user_register border_y"> 
<div> 
<span style="color:green;"> after two seconds then auto redirect </span><br><br> 

<a href="http://example.com/down/test.html">if you don't want to wait you can click this。</a></div></div> 

我想使用jQuery来获得:经过两秒钟,然后自动重定向到a标签页。我应该怎么做?

回答

14

你甚至不需要jQuery;香草JS将正常工作......

<a id="link" href="http://example.com">Go NOW!!!</a> 

JS:

window.setTimeout(function() { 
location.href = document.getElementsByClassName("user_register border_y")[0].getElementsByTagName("a")[0].href; 
}, 2000); 

getElementsByClassName在所有浏览器无法正常工作;所以一定要确保你提供一个fallback

+3

的setInterval不这样做的正确方法。你想要一个单次计时器,而不是一个重复的计时器,它将会是setTimeout,而不是setInterval。 – jfriend00

+1

就像jQuery一样优雅,除非它是一个非常需要它的页面(即大量的脚本动作/事件),否则我不会介绍它。但是,我会建议setTimeout。 – Kris

+0

你是对的;我听说过有关setTimeout很糟糕的一些事情,但我认为这是一个很好的习惯。更新。 –

12

使用setTimeout

setTimeout(function() { 
    window.location.href = $("a")[0].href; 
}, 2000); 
+0

karim79,你能告诉我为什么使用2000不是2,因为这是两秒 – zhuanzhou

+0

@zhuanzhou - 'setTimeout'预计参数为毫秒,2000毫秒== 2秒。 – karim79

+0

明白了,非常感谢。 – zhuanzhou

11

为什么使用JavaScript?

<head> 
    <meta http-equiv="refresh" content="2;url=http://example.com/down/test.html"> 
</head> 

<body> 

    <div class="user_register border_y"> 
    <div> 
    <span style="color:green;"> after two seconds then auto redirect </span><br><br> 

    <a href="http://example.com/down/test.html">if you don't want to wait you can click this。</a></div></div> 
+0

对不起,页面是动态的 – zhuanzhou

+0

'meta refresh'是不可靠的,例如,在IE中,我可以关闭它。 – Mrchief

+2

@Mrchief:你也可以关闭JavaScript。 ; o) – user113716

3

下面是基于把你介绍一个简单的脚本:

function redirect(){ 
    window.location = $('a').attr('href'); 
} 

setTimeout(redirect, 2000); 

演示:http://jsfiddle.net/KesU9/

+0

我编辑了你的代码来读取'setTimeout(redirect,2000)'。前面的代码有'redirect()',一旦超时被设置,它就会运行重定向函数,而不是简单地将重定向分配给超时。 –

+0

哎呀,很好。 – RobB

1

使用上身体的OnLoad这个简单的代码

<body onLoad="setTimeout(location.href='http://www.newpage.com', '2000')"> 
0

使用JavaScript重定向。 例如:

<script type="text/javascript"> 
var time = 15; // Time coutdown 
var page = "http://www.redirect-url.com/"; 
function countDown(){ 
time--; 
gett("timecount").innerHTML = time; 
if(time == -1){ 
window.location = page; 
} 
} 
function gett(id){ 
if(document.getElementById) return document.getElementById(id); 
if(document.all) return document.all.id; 
if(document.layers) return document.layers.id; 
if(window.opera) return window.opera.id; 
} 
function init(){ 
if(gett('timecount')){ 
setInterval(countDown, 1000); 
gett("timecount").innerHTML = time; 
} 
else{ 
setTimeout(init, 50); 
} 
} 
document.onload = init(); 
</SCRIPT> 

体片后添加以下代码

<h3>Auto redirect after <span id="timecount"></span> second(s)!</h3> 
相关问题