【问题标题】:Dynamically change content and replace current URL动态更改内容并替换当前 URL
【发布时间】:2016-11-17 06:05:40
【问题描述】:

所以我想要实现的是有一个链接列表,点击其中任何一个都会将 div 的内容更改为“随便”。很简单,我已经做到了。

我遇到问题的部分是获取更改内容的某种永久链接。

 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(如果这实际上是这样做的方式 - 我可能是错的),或者如果有其他方法我可以尝试实现这一点。

提前致谢。

【问题讨论】:

  • 这个 SO question 可以帮助你。
  • window.history.pushState("object or string", "Title", "/new-url");

标签: javascript jquery ajax html5-history


【解决方案1】:

使用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的信息。

【讨论】:

  • 我明白了。我有点理解这一点,一个问题:如果我实现这个然后向某人发送一个链接,例如 www.example.com/something.html,并且他们以前从未访问过该网站,那会将他们带到已更改的页面内容还是只是用不同的 url 为他们提供索引页面?
  • 其实我只是想通了。事实证明它比我想象的要简单得多。感谢您的帮助。
猜你喜欢
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 2012-10-11
  • 2011-05-22
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多