2011-08-06 56 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> 
相關問題