在 URL 中添加项目而不重新加载页面 (pushState)

Add items in URL without page reload (pushState)

我有一个功能可以在我的 URL 中添加项目而无需重新加载页面。 我在过滤功能中使用它。每当有人点击过滤器中的一个项目时,此函数将在 URL 中添加点击的项目。 如果再次单击同一个项目,该项目将再次消失。

function childboxes(MainElement, ChildElement){
    var pathArray = window.location.pathname.split( '/' );
    var extra = pathArray[2];       
    var clicked = "&"+MainElement+'='+ChildElement;
    var re = new RegExp(clicked, 'g');       

    if(extra.match(re)){   
        //remove item from URL        
        var extra = extra.replace(clicked, "");
        window.history.replaceState(null, null, extra);

    }else{
        //Add items in URL  
         window.history.pushState(null, null, extra+"&"+MainElement+'='+ChildElement);
    }        
}

示例: http://www.domain.com/en/webshop&brand=18&category=shoes&product=test

这是我的问题,每个添加的项目都会添加:&brand=18 众所周知,第一个参数必须以“?”开头而不是“&”。

我不知道如何确保第一项以问号开头。

然后使用其他东西 pushStatereplaceState 对我来说没问题。我唯一想要的是当我们更新 URL 时页面没有重新加载。

简单检查:

window.history.pushState(null, null, extra+ ( extra.indexOf("?")>-1 ? "&" : "?" ) +MainElement+'='+ChildElement);

编辑:

正则表达式已修复:

var clicked = "[&\?]"+MainElement+'='+ChildElement;

并且:

var extra = extra.replace(re, ""); // you can replace by regex

编辑2:

清理

function childboxes(MainElement, ChildElement){
    var extra = window.location.pathname + window.location.search;
    var regex = new RegExp("[&\?]"+MainElement+'='+ChildElement, 'g');       

    extra = extra.replace(regex, "");
    extra = extra+ ( extra.indexOf("?") > -1 ? "&" : "?" ) +MainElement+ '=' +ChildElement;
    window.history.pushState(null, null, extra);
}

编辑3:

replaceState

function childboxes(MainElement, ChildElement){
    var extra = window.location.pathname + window.location.search;
    var regex = new RegExp("[&\?]"+MainElement+'='+ChildElement, 'g');

    var isReplace = extra.match(regex);
    extra = extra.replace(regex, "");
    extra = extra+ ( extra.indexOf("?") > -1 ? "&" : "?" ) +MainElement+ '=' +ChildElement;
    window.history[isReplace?'replaceState':'pushState'](null, null, extra);
}