更新url中的查询字符串

时间:2015-05-17 14:28:21

标签: javascript html5

我想点击复选框更新网址查询字符串。这是代码,它无法正常工作

param1=param1=true
param1=param1=param1=false
param1=param1=param1=param1=true

而不是:

param1=false
param1=true

这是一个无意义的代码:

if (this.checked) {
      if (window.location.href.search('[?&]') === -1) {
        window.history.pushState('object or string', 'Title', window.location.href + '?param1=true');  
      } else {
        window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=true'));   
      }

    } else {
      if (window.location.href.search('[?&]') === -1) {
        window.history.pushState('object or string', 'Title', window.location.href + '?param1=false');  
      } else {
        window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=false'));   
      }
    }

2 个答案:

答案 0 :(得分:2)

考虑一下:

> 'param1=false'.replace(/param1=false|true/i, 'param1=true')
"param1=true"
> 'param1=true'.replace(/param1=false|true/i, 'param1=true')
"param1=param1=true"
> 'true'.replace(/param1=false|true/i, 'param1=true')
"param1=true"

问题是您的正则表达式接受param1=falsetrue。您需要将false|true部分放在一个组中(在括号中),以使|也不适用于param1=部分。所以你的正则表达式应该是/param1=(false|true)/i

> 'param1=true'.replace(/param1=(false|true)/i, 'param1=true')
'param1=true'

答案 1 :(得分:0)

如果您的查询字符串中没有其他参数,您可以像这样重建您的网址:

var href = window.location.protocol + '//' + window.location.host + window.location.pathname;
if (this.checked) {
    window.history.pushState('object or string', 'Title', href + '?param1=true');  
} else {
    window.history.pushState('object or string', 'Title', href + '?param1=false');   
}