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

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

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

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

虽然我已经使用了 jQuery 的 window.load ()函数,但是我仍然没有得到我想要的。

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

有人能告诉我怎样才能等5秒钟吗。

267167 次浏览

你实际上需要在 window.setTimeout()中传递一个函数,你想在5000毫秒后执行它,像这样:

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

更多信息: .setTimeout()

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

您需要向 setTimeout传递一个函数

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

看起来你就快到了,试试看:

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);


}

您可以使用这个 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>

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

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

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

<script type="text/javascript">
function idleTimer() {
var t;
//window.onload = resetTimer;
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer;     // catches mouse clicks
window.onscroll = resetTimer;    // catches scrolling
window.onkeypress = resetTimer;  //catches keyboard actions


function logout() {
window.location.href = 'logout.php';  //Adapt to actual logout script
}


function reload() {
window.location = self.location.href;  //Reloads the current page
}


function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 1800000);  // time is in milliseconds (1000 is 1 second)
t= setTimeout(reload, 300000);  // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();
</script>
setTimeout('Redirect()', 1000);
function Redirect()
{
window.location="https://stackoverflow.com";
}

//document.write (“您将在1000-> 1秒,2000-> 2秒内重定向到一个新页面”) ;