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

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

本文关键字:加载 URL 参数 添加 JavaScript jQuery 使用      更新时间:2023-09-26

目前,我使用以下代码在页面加载后在URL末尾添加主题标签:

window.location.hash = 'mobile';

或者,我需要在 URL 的末尾添加一个参数,例如

"&location=mobile"

我该如何去做这样的事情?谢谢

有关更多信息,请参阅此内容,但现在可以在大多数现代浏览器中完成: 修改网址而不重新加载页面

使用 HTML5:

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

除非你在引用历史时需要该对象,否则你可以将其留空,并且标题实际上当前也没有更改任何内容,因此您可能不需要它。从本质上讲,您只需要您在这种情况下最有可能的第 3 个参数。如果你想看到它工作,把它保存为一个html文件并运行它(JSFiddle由于某种原因不会显示它):

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
history.pushState("", "", "lookiehere.html");
</script>
</head>
<body>
  Look, I changed!

</body>
</html>

或者保留当前 uri 并添加到其中:

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

或者,要仅保留文件夹结构而不保留任何页面 URL,请执行以下操作:

    var loc = window.location.pathname,
    dir = loc.substring(0, loc.lastIndexOf('/'));
history.pushState("", "", dir+"/whatever");

编辑:如果您担心浏览器支持/internet-explorer,那么历史记录.js可能与您的兴趣相关:https://github.com/browserstate/history.js