简体   繁体   中英

With JavaScript or jQuery how to add a parameter to the URL after the page loads

Currently I'm using the following code to add a hashtag at the end of the URL after the page loads:

window.location.hash = 'mobile';

Alternatively, I need to add a parameter at the end of the URL, something like

"&location=mobile"

How would I go about doing something like that? Thank you

See this for more information, but it can be done in most modern browsers now: Modify the URL without reloading the page

With HTML5:

window.history.pushState("object or string", "Title", "/new-url");

Unless you need the object when refering back to the history you can leave that blank, and the title doesn't actually currently change anything either so you probably don't need that. Essentially you just need the 3rd parameter most likely in your case. If you want to see it work, save this as an html file and run it (JSFiddle won't display it for some reason):

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

history.pushState("", "", "lookiehere.html");

</script>
</head>
<body>

  Look, I changed!


</body>
</html>

Or to keep the current uri and add to it:

    history.pushState("", "", "/"+window.location.pathname.substr(1)+"lookiehere.html");

Or, to keep just the folder structure but not any page url:

    var loc = window.location.pathname,
    dir = loc.substring(0, loc.lastIndexOf('/'));

history.pushState("", "", dir+"/whatever");

Edit: If you're worried about browser support/internet-explorer then History.js might be relevant to your interests: https://github.com/browserstate/history.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM