【问题标题】:Append parameter in url without reloading page在 url 中附加参数而不重新加载页面
【发布时间】:2012-05-13 18:51:16
【问题描述】:

我正在使用以下代码将参数附加到 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后 我想要网址:“..../search.php#t_2”

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

【问题讨论】:

  • 我想在 url 中添加多个参数,例如:

标签: javascript jquery url append pushstate


【解决方案1】:

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

【讨论】:

  • 我认为OP只想将片段附加到url,例如document.location.href += '#txt'
  • @NADH 他从未说过 - 代码(和原始问题)谈论的是查询参数,而不是锚片段。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2020-03-06
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多