Javascript 等待两秒钟然后在 jquery 中自动重定向另一个页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6964457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
waiting two seconds then auto redirect another page in jquery?
提问by zhuanzhou
the html structure:
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>
i want to use jquery to get: after two seconds then auto redirect to the a
label page. how should i do?
我想使用 jquery 获取:两秒后自动重定向到a
标签页面。我应该怎么做?
回答by Thomas Shields
You don't even need jQuery; vanilla JS will work fine...
你甚至不需要 jQuery;vanilla JS 可以正常工作...
<a id="link" href="http://example.com">Go NOW!!!</a>
JS:
JS:
window.setTimeout(function() {
location.href = document.getElementsByClassName("user_register border_y")[0].getElementsByTagName("a")[0].href;
}, 2000);
getElementsByClassName
doesn't work in all browsers; so make sure you provide a fallback
getElementsByClassName
不适用于所有浏览器;所以确保你提供了一个后备
回答by karim79
Use setTimeout
:
使用setTimeout
:
setTimeout(function() {
window.location.href = $("a")[0].href;
}, 2000);
回答by user113716
Why use JavaScript?
为什么要使用 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>
回答by RobB
Below is a simple script based off of your description:
以下是基于您的描述的简单脚本:
function redirect(){
window.location = $('a').attr('href');
}
setTimeout(redirect, 2000);
回答by shuseel
Use this simple code on body OnLoad
在身体 OnLoad上使用这个简单的代码
<body onLoad="setTimeout(location.href='http://www.newpage.com', '2000')">
回答by V? V?
Use JavaScript to redirect. For example:
使用 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>
add this code after body tab
在正文选项卡后添加此代码
<h3>Auto redirect after <span id="timecount"></span> second(s)!</h3>