X 秒后使用 JavaScript 等待页面重定向

IT技术 javascript jquery
2021-02-25 01:54:46

我需要在输入错误消息 5 秒后重定向到特定的 url。首先,我使用了 Javascript,如下所示。

document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000));

但它不会等待 5 秒。比我在谷歌搜索这个问题之后才知道在 DOM 上加载文档时调用了“document.ready()”,而不是在 Web 浏览器上。

比我使用过 jQuery 的 window.load() 函数,但我仍然没有得到我想要的。

$(window).load(function() {
               window.setTimeout(window.location.href = "https://www.google.co.in",5000);
            });

任何人都可以让我知道我需要做什么才能等待 5 秒钟。

6个回答

看起来你快到了。尝试:

if(error == true){

    // Your application has indicated there's an error
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "https://www.google.co.in";

    }, 5000);

}
谢谢,我把它和 PHP 结合起来了: if ($row_cnt>0) { echo "Already Posted!"; echo "<meta http-equiv='refresh' content='1; URL=new.php'>"; 出口(); }
2021-04-19 01:54:46
html 替代 <meta http-equiv="refresh" content="4; URL=../device_user/email_keyboard_one_pint.html">
2021-05-14 01:54:46

您实际上需要window.setTimeout()在 5000 毫秒后传递一个要在 5000 毫秒后执行的函数,如下所示:

$(document).ready(function () {
    // Handler for .ready() called.
    window.setTimeout(function () {
        location.href = "https://www.google.co.in";
    }, 5000);
});

欲了解更多信息: .setTimeout()

打败我。重定向不会等待,因为会立即分配位置。它必须是一个函数调用
2021-04-27 01:54:46

您可以使用此 JavaScript 函数。在这里,您可以向用户显示重定向消息并重定向到给定的 URL。

<script type="text/javascript">   
    function Redirect() 
    {  
        window.location="http://www.newpage.com"; 
    } 
    document.write("You will be redirected to a new page in 5 seconds"); 
    setTimeout('Redirect()', 5000);   
</script>

您需要将函数传递给 setTimeout

$(window).load(function () {
    window.setTimeout(function () {
        window.location.href = "https://www.google.co.in";
    }, 5000)
});

使用 JavaScriptsetInterval()方法在指定时间后重定向页面。以下脚本将在 5 秒后重定向页面。

var count = 5;
setInterval(function(){
    count--;
    document.getElementById('countDown').innerHTML = count;
    if (count == 0) {
        window.location = 'https://www.google.com'; 
    }
},1000);

可以从这里找到示例脚本和现场演示 -使用 JavaScript 延迟后重定向页面