2

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

window.location.hash = 'mobile';

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

"&location=mobile"

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

4

1 回答 1

4

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

使用 HTML5:

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

除非您在参考历史记录时需要该对象,否则您可以将其留空,并且标题当前实际上也没有更改任何内容,因此您可能不需要它。本质上,您最有可能只需要第三个参数。如果你想看到它工作,将它保存为一个 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,那么 History.js 可能与您的兴趣相关:https ://github.com/browserstate/history.js

于 2013-10-16T20:01:13.717 回答