2011-09-01 47 views
46

是否有使用jQuery一个给一段时间后重定向到一个特定的URL的方式?JQuery的重定向到URL后指定时间

+0

你应该接受正确的答案... – Legionar

+0

如果你想跨浏览器和搜索引擎优化支持:[重定向发生器(HTTP: //insider.zone/tools/client-side-url-redirect-generator/) –

回答

91

您可以使用setTimeout()功能:

// Your delay in milliseconds 
var delay = 1000; 
setTimeout(function(){ window.location = URL; }, delay); 
+2

笑几乎相同但在24秒快速:P –

45

你并不真正需要的jQuery这一点。你可以使用setTimeout方法与普通的JavaScript做到这一点:

// redirect to google after 5 seconds 
window.setTimeout(function() { 
    window.location.href = 'http://www.google.com'; 
}, 5000); 
12
$(document).ready(function() { 
    window.setInterval(function() { 
    var timeLeft = $("#timeLeft").html();         
     if(eval(timeLeft) == 0){ 
       window.location= ("http://www.technicalkeeda.com");     
     }else{    
      $("#timeLeft").html(eval(timeLeft)- eval(1)); 
     } 
    }, 1000); 
}); 
+2

我不鼓励使用eval'()'因为它有很多危险的后果。相反,我会推荐使用'parseInt()'。 – winhowes

+0

非常感谢。 – Roni

4

只需使用:

setTimeout("window.location.href='yoururl';",4000); 

..where的 '4000' 是m.second

6

您可以使用

$(document).ready(function(){ 
     setTimeout(function() { 
     window.location.href = "http://test.example.com/;" 
     }, 5000); 
    }); 
2

我做了一个si多个演示,提示X秒数并重定向以设置url。如果您不想等到计数结束,只需点击计数器即可立即重定向。 简单的计数器,可以在页面中间点时间倒计时。 您可以在点击或加载某个页面时运行它。

LIVE DEMO ONLOAD

LIVE DEMO ONCLICK

我为此也做了GitHub库: https://github.com/GlupiJas/redirect-counter-plugin

JS代码示例:

// FUNCTION CODE 
function gjCountAndRedirect(secounds, url) 
{ 

     $('#gj-counter-num').text(secounds); 

     $('#gj-counter-box').show(); 

    var interval = setInterval(function() 
    { 

     secounds = secounds - 1; 

     $('#gj-counter-num').text(secounds); 

     if(secounds == 0) 
     { 

      clearInterval(interval); 
      window.location = url; 
      $('#gj-counter-box').hide(); 

     } 

    }, 1000); 

    $('#gj-counter-box').click(function() //comment it out -if you dont want to allo count skipping 
    { 
     clearInterval(interval); 
     window.location = url; 

    }); 
} 

// USE EXAMPLE 
$(document).ready(function() { 
    //var 
    var gjCountAndRedirectStatus = false; //prevent from seting multiple Interval 

    //call 
    $('h1').click(function(){ 
     if(gjCountAndRedirectStatus == false) 
     { 
      gjCountAndRedirect(10, document.URL); 
      gjCountAndRedirectStatus = true; 
     } 
    }); 

}); 
1

是,该解决方案是使用setTimeout,像这样:

var delay = 10000; 
var url = "https://stackoverflow.com"; 
var timeoutID = setTimeout(function() { 
    window.location.href = url; 
}, delay); 

注意,结果被存储到timeoutID。如果出于某种原因,你需要取消订单,你只需要调用

clearTimeout(timeoutID);