在不重新加载页面的情况下在url中附加参数

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

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
  • LINK2
  • LINK3

我想要url:“…. / search.php”

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

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

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

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

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

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