سؤال

is it possible to change parameter in url bar so button onclick the parameter to get changed ? So far I have this:

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 is correct but how to make it change in the url bar? Is it possible at all without page reload? thanks in advance !

هل كانت مفيدة؟

المحلول

Take a look at window.history.pushState()

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

This allows you to change the URL in the address bar without reloading the page.

Here's the current support: http://caniuse.com/#search=pushstate

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

So for you something like

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

Firefox currently does use the Page Title but you could set it in the state object then use window.onpopstate to get the state object and set the page title (if you need to).

If you need to support older IE browsers there's a few libraries that can help you out (like history.js)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top