简体   繁体   English

使用JavaScript或jQuery,如何在页面加载后向URL添加参数

[英]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: 当前,我正在使用以下代码在页面加载后在URL的末尾添加一个#号标签:

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 有关更多信息,请参见此内容,但是现在可以在大多数现代浏览器中完成: 修改URL而无需重新加载页面

With HTML5: 使用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): 如果您希望它正常工作,请将其另存为html文件并运行(JSFiddle由于某种原因不会显示它):

<!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: 或保留当前uri并添加到其中:

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

Or, to keep just the folder structure but not any page url: 或者,仅保留文件夹结构,而不保留任何页面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 编辑:如果您担心浏览器支持/互联网浏览器,那么History.js可能与您的兴趣有关: https : //github.com/browserstate/history.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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