1

我正在使用以下代码将参数附加到 url。这工作正常,但是当在 url 中附加参数时,页面正在重新加载。我想在不重新加载页面的情况下使用此功能。

function insertParam(key, value)
{
    key = escape(key); value = escape(value);

    var kvp = document.location.search.substr(1).split('&');


    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
                x[1] = value;
                kvp[i] = x.join('=');
                    alert('sdfadsf');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&'); 
    //alert(document.location.href);

}

我想在不重新加载页面的情况下向 url 添加多个参数,例如:

  • txt1
  • txt2
  • txt3
  • 链接1
  • 链接2
  • 链接3

我想要网址:“..../search.php”

单击 txt2 后,我想要 url:“..../search.php#t_2”

点击link2后我想要网址:“..../search.php#t_1&l_2”

4

2 回答 2

6

您只能使用history.pushState(state, title, url)HTML5 功能来执行此操作。

于 2012-05-04T08:22:45.567 回答
0

有一个新功能旨在用location.hash更好的解决方案代替使用:pushState.

 window.history.pushState(data, "Title", "/new-url");

更多信息:http ://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate

于 2013-12-25T09:15:02.460 回答