在浏览器中更改 URL 而不使用 JavaScript 加载新页面 [英] Change the URL in the browser without loading the new page using JavaScript

查看:22
本文介绍了在浏览器中更改 URL 而不使用 JavaScript 加载新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能有一个 JavaScript 操作,它可能对当前页面有一些影响,但不会还要更改浏览器中的 URL,因此如果用户点击重新加载或添加书签,则使用新的 URL?

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?

如果后退按钮能重新加载原始 URL 也很好.

It would also be nice if the back button would reload the original URL.

我正在尝试在 URL 中记录 JavaScript 状态.

I am trying to record JavaScript state in the URL.

推荐答案

在 HTML 5 中,使用 history.pushState 函数.举个例子:

With HTML 5, use the history.pushState function. As an example:

<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
   history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>

和一个 href:

<a href="#" id='click'>Click to change url to bar.html</a>

<小时>

如果您想在不向后退按钮列表中添加条目的情况下更改 URL,请改用 history.replaceState.

这篇关于在浏览器中更改 URL 而不使用 JavaScript 加载新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆