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

zhu*_*hou 10 javascript jquery

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>
Run Code Online (Sandbox Code Playgroud)

我想使用jquery获取:两秒钟后自动重定向到a标签页面.我应该怎么做?

Tho*_*lds 16

你甚至不需要jQuery; 香草JS会很好......

<a id="link" href="http://example.com">Go NOW!!!</a>
Run Code Online (Sandbox Code Playgroud)

JS:

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

getElementsByClassName不适用于所有浏览器; 所以一定要提供后备

  • setInterval不是正确的方法.你想要一次性计时器,而不是一个重复计时器,它将是setTimeout,而不是setInterval. (3认同)

kar*_*m79 15

用途setTimeout:

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


use*_*716 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>
Run Code Online (Sandbox Code Playgroud)

  • @Mrchief:你也可以关掉JavaScript.; O) (2认同)
  • 是的,但默认情况下没有关闭.此外,你不能忍住关闭js而这个设置 - 没有人关心! (2认同)