如何在javascript中替换url?

时间:2013-12-23 10:09:47

标签: javascript

我想在加载时将URL替换为另一个URL。 我写了下面的代码。

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

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

2 个答案:

答案 0 :(得分:3)

转到新页面时,不会保留executed变量。即使它是,var executed = false再次将其设置为假:p

请改为尝试:

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

答案 1 :(得分:1)

只是你在页面重新加载后重置了变量。尝试检查这样的GET参数:

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