简体   繁体   English

为什么这个小重定向不起作用(javascript)?

[英]Why isn't this small redirect working (javascript)?

function redir(){
setTimeout(window.location = '/SV/main/main.html', 10);
}

I dont know if the delay is in miliseconds or seconds, but I have tried BOTH. 我不知道延迟是在几毫秒还是几秒钟,但我已经尝试了。 (by adding three zeros). (通过添加三个零)。

Problem is, the redirect is made right away, without any delay at all... why? 问题是,重定向是立即完成的,没有任何延迟......为什么?

Thanks 谢谢

BTW its called like this: <body onload="redir();"> BTW它的调用方式如下: <body onload="redir();">

You have to put your javascript statement between quotes : 你必须把你的javascript语句放在引号之间:

function redir(){
    setTimeout("window.location = '/SV/main/main.html';", 10);
}

The delay is in milliseconds btw. 延迟是以毫秒为单位。

As said in the comments and other answers, it is much cleaner to use an anonymous function to do such things : 正如在评论和其他答案中所说,使用匿名函数执行此类操作要简单得多:

function redir() {
  setTimeout(function(){
    window.location = "/SV/main/main.html";
  }, 10); // 10 milliseconds
}

Much cleaner way to write this: 更清洁的方式写这个:

function redir() {
  setTimeout(function(){
    window.location = "/SV/main/main.html";
  }, 10000); // fire after 10 seconds
}

Try 尝试

setTimeout(function(){window.location = '/SV/main/main.html';}, 10);

10 is milliseconds. 10是毫秒。

setTimeout takes a function and a timeout interval. setTimeout采用函数和超时间隔。

function redir() {
    setTimeout(function() {
        window.location = '/SV/main/main.html';
    }, 10);
}

您应该使用location的href属性,并将代码包装在函数中。

window.setTimeout( function() { window.location.href = '/SV/main/main.html';} , 10 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM