gpt4 book ai didi

javascript - History API 和 History.js 后退按钮问题

转载 作者:数据小太阳 更新时间:2023-10-29 05:19:34 28 4
gpt4 key购买 nike

我正在通过 Ajax 加载页面。当用户单击链接时,页面已成功加载 AJAX,但当用户单击后退按钮时,页面会重新加载初始页面。所以场景是这样的。

  1. 载入初始页面(index.php)
  2. 用户点击链接
  3. 页面加载成功
  4. 点击后退按钮
  5. 初始页面现在显示两次。

这是标记。

    $(function() {
// Prepare
var History = window.History; // Note: We are using a capital H instead of a lower h
if (!History.enabled) {
// History.js is disabled for this browser.
// This is because we can optionally choose to support HTML4 browsers or not.
return false;
}

// Bind to StateChange Event
History.Adapter.bind(window, 'statechange', function() { // Note: We are using statechange instead of popstate
var State = History.getState();
$('#content').load(State.url);
});

$('a').click(function(evt) {
evt.preventDefault();
History.pushState(null, $(this).text(), $(this).attr('href'));
alert(State.url)
});
});

这是标记

   <div id="wrap">
<a href="page1.html">Page 1</a>
</div>

<div id="content">
<p>Content within this box is replaced with content from
supporting pages using javascript and AJAX.</p>
</div>

如果你还是不明白我的问题或情景

这是完整的场景。初始页

enter image description here

当用户单击链接时,所选页面加载成功

enter image description here

当我点击后退按钮时,初始页面现在翻了一番

enter image description here

如您所见,“Page1”链接加倍了。这是浏览器的问题吗?或者我对历史 api 的理解是缺乏或缺失的?可能的解决方案是什么?

最佳答案

如果您构建您的站点以对主要页面和内容页面使用类似的模板,您可以使用 jquery.load 的容器选择器语法:

// See: http://api.jquery.com/load/
$('#result').load('ajax/test.html #container');

在您的情况下会导致:

$('#content').load(State.url + ' #content');

这将带来额外的好处,即内容 url 页面也可以直接访问,而无需添加太多技巧。

关于javascript - History API 和 History.js 后退按钮问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028024/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com