等待两秒钟,然后在jquery中自动重定向另一个页面

waiting two seconds then auto redirect another page in jquery?

本文关键字:重定向 另一个 两秒钟 然后 jquery 等待      更新时间:2023-09-26

HTML结构:

<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标签页面。我该怎么办?

你甚至不需要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不能在所有浏览器中工作;所以要确保你提供了一个备用的

使用setTimeout:

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

为什么使用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>

下面是一个基于你的描述的简单脚本:

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

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

主体OnLoad

使用下面的简单代码
<body onLoad="setTimeout(location.href='http://www.newpage.com', '2000')">

使用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>

在body tab

之后添加以下代码
<h3>Auto redirect after <span id="timecount"></span> second(s)!</h3>