动态更改内容并替换当前 URL
Dynamically change content and replace current URL
所以我想要实现的是有一个链接列表,单击其中任何一个都会将 div 的内容更改为 'whatever'。很简单,我做到了
我遇到问题的部分是获取更改内容的某种固定链接。
say main domain is www.example.com
then you click link X and content Y shows up on the page
then the URL should change to www.example.com/SOMETHINGHERE
--all good so far--
then using the new link should take you to the site with the changed content
让我们获取一些示例代码:
<a href="something.html" class="linx" >Click me</a>
<a href="something2.html" class="linx" > Click me too</a>
<div id="loadhere"></div>
$('.linx').click(function (event) {
event.preventDefault();
$('#loadhere').load(this.href);
});
非常基本的东西。这就是它的工作方式。现在我用谷歌搜索了一下,看来我需要使用历史 API 甚至 history.js 库。我做了一些修改,但我是新手,整个历史的事情有点混乱。
一个接近我想要实现的例子是Soulwire's personal website.
导航到实验部分,看看 运行 每个实验是如何工作的。
所以基本上我要问的是你是否可以通过给我一个例子或其他东西来帮助我使用历史 api(如果这实际上是这样做的方式——我可能是错的)不仅仅是链接文档,或者如果有其他方法我可以尝试实现这一点。
提前致谢。
使用 window.history.pushState()
功能,您可以更改地址栏中的内容。 pushState() 指的是将站点所处的状态推送到历史记录中的操作,以便用户可以使用浏览器导航按钮进行导航:
history.pushState(stateObj, 'page title', 'pathname');
因此将其实施到您的代码中:
$('.linx').click(function (event) {
event.preventDefault();
$('#loadhere').load(this.href);
// use push state here
var stateObj = {'foo': 'bar'};
history.pushState(stateObj, this.href.replace('.html', ''), this.href);
});
stateObject
可以存储一些定义您的站点所处状态的数据,即。勾选的复选框或滚动状态。
您可以使用 history.state
访问此对象。所以对于上面的例子:
history.state.foo = "bar"
请注意,这是现代网络标准,必须采取措施确保与旧版浏览器的兼容性。
详细了解 history.pushState()
here。
所以我想要实现的是有一个链接列表,单击其中任何一个都会将 div 的内容更改为 'whatever'。很简单,我做到了
我遇到问题的部分是获取更改内容的某种固定链接。
say main domain is www.example.com
then you click link X and content Y shows up on the page
then the URL should change to www.example.com/SOMETHINGHERE
--all good so far--
then using the new link should take you to the site with the changed content
让我们获取一些示例代码:
<a href="something.html" class="linx" >Click me</a>
<a href="something2.html" class="linx" > Click me too</a>
<div id="loadhere"></div>
$('.linx').click(function (event) {
event.preventDefault();
$('#loadhere').load(this.href);
});
非常基本的东西。这就是它的工作方式。现在我用谷歌搜索了一下,看来我需要使用历史 API 甚至 history.js 库。我做了一些修改,但我是新手,整个历史的事情有点混乱。
一个接近我想要实现的例子是Soulwire's personal website. 导航到实验部分,看看 运行 每个实验是如何工作的。
所以基本上我要问的是你是否可以通过给我一个例子或其他东西来帮助我使用历史 api(如果这实际上是这样做的方式——我可能是错的)不仅仅是链接文档,或者如果有其他方法我可以尝试实现这一点。
提前致谢。
使用 window.history.pushState()
功能,您可以更改地址栏中的内容。 pushState() 指的是将站点所处的状态推送到历史记录中的操作,以便用户可以使用浏览器导航按钮进行导航:
history.pushState(stateObj, 'page title', 'pathname');
因此将其实施到您的代码中:
$('.linx').click(function (event) {
event.preventDefault();
$('#loadhere').load(this.href);
// use push state here
var stateObj = {'foo': 'bar'};
history.pushState(stateObj, this.href.replace('.html', ''), this.href);
});
stateObject
可以存储一些定义您的站点所处状态的数据,即。勾选的复选框或滚动状态。
您可以使用 history.state
访问此对象。所以对于上面的例子:
history.state.foo = "bar"
请注意,这是现代网络标准,必须采取措施确保与旧版浏览器的兼容性。
详细了解 history.pushState()
here。