【问题标题】:Changing url parameter with js without reloading page on button click [duplicate]使用js更改url参数而无需在按钮单击时重新加载页面[重复]
【发布时间】:2014-06-24 02:42:15
【问题描述】:

是否可以更改 url 栏中的参数,以便单击参数以进行更改?到目前为止,我有这个:

function change_product(){
var url =  'http://www.example.com/index.php?product=805';
var newSrc = '0';
newurl=url.replace(/(product=)[^\&]+/,'$1' + newSrc)
alert(newurl);
}    

<button class="save" type="BUTTON" onclick="change_product();">Copy</button>    

newurl 是正确的,但如何在 url 栏中更改?没有页面重新加载是否有可能? 提前致谢!

【问题讨论】:

  • 在建议的答案中我只看到重新加载解决方案
  • 没有。 location.hash 和 pushstate 都在建议的副本中

标签: javascript jquery url url-rewriting


【解决方案1】:

看看window.history.pushState()

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

这允许您更改地址栏中的 URL 而无需重新加载页面。

这是当前的支持:http://caniuse.com/#search=pushstate

var state = {}, newUrl = "test.html";
window.history.pushState(state, "Page Title", newUrl);

所以对你来说

function change_product(){
    var productId = 805;
    window.history.pushState({productId: productId} , "", "?product=" + productId);
}

Firefox 目前确实使用页面标题,但您可以在状态对象中设置它,然后使用 window.onpopstate 获取状态对象并设置页面标题(如果需要)。

如果您需要支持较旧的 IE 浏览器,有一些库可以帮助您(例如 history.js)

【讨论】:

  • 干得好是的!这行得通!谢谢!
猜你喜欢
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2013-04-25
相关资源
最近更新 更多