历史API和History.js后退按钮问题

Kye*_*JmD 6 javascript ajax jquery history.js

我正在通过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)
            });
        });
Run Code Online (Sandbox Code Playgroud)

这是标记

   <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>
Run Code Online (Sandbox Code Playgroud)

如果你仍然没有得到我的问题或情景

这是完整的方案.初始页面

在此输入图像描述

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

在此输入图像描述

当我单击后退按钮时,初始页面现在加倍

在此输入图像描述

如您所见,"Page1"链接加倍.这是一个浏览器问题吗?或者我对历史api的不足之处是缺乏或缺失的东西?这有什么可能的解决方案?

Roo*_*aan 5

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

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

在您的情况下会导致:

$('#content').load(State.url + ' #content');
Run Code Online (Sandbox Code Playgroud)

这将带来额外的好处,即内容URL页面也可以直接访问,而不会增加太多技巧.