2013-12-23 23 views
0

我想在加载时用另一个URL替换URL。 我已经写下了下面的代码。如何更换JavaScript中的网址?

<script type="text/javascript"> 
    var executed = false; 
    if (!executed) { 
     executed = true; 
     window.location.href = window.location.pathname + '?'+'bc'; 
      } 
</script> 

但它工作不正常。它一次又一次地加载。它不停止。

+2

更改URL将导致浏览器将用户指向该位置,从而导致无限循环。你应该使用'window.history'状态:http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/ – CodingIntrigue

+0

好吧,它会一次又一次地加载,因为变量被重置在页面load.Try保持执行一些cookie – iJade

回答

3

进入新页面时,不会保留executed变量。即使是这样,var executed = false只是将其设置为再次假:P

试试这个:

if(!window.location.search.match(/\?bc$/)) { 
    window.location.href = window.location.pathname+"?bc"; 
} 
1

只要你变量重新加载页面后复位。尝试检查这样的GET参数:

if (window.location.search.indexOf('?bc') === -1) { 
    window.location.href = window.location.pathname + '?bc'; 
} 
+0

其工作..谢谢。 –