13

我在使用 jQuery 的 history.js 时遇到了一点麻烦。我只是想让导航集与后退按钮一起工作(他们似乎做得很好)。然而。当我单击后退按钮时,url 会更改为旧的(这又是好的,也是我想要的),但内容并没有按照应有的方式替换。

为了使这更容易理解,这里有一些代码。

    <ul class="content_links">
        <li><a href="/historyapi/pages/content_page_1.html">Content page 1</a></li>
        <li><a href="/historyapi/pages/content_page_2.html">Content page 2</a></li>
        <li><a href="/historyapi/pages/content_page_3.html">Content page 3</a></li>
        <li><a href="/historyapi/pages/content_page_4.html">Content page 4</a></li>
        <li><a href="/historyapi/pages/content_page_5.html">Content page 5</a></li>
    </ul>
    <div id="content">
        <p>Content within this box is replaced with content from supporting pages using javascript and AJAX.
    </div>

显然,我想要的是将页面内容加载到内容中,使用 .load() 可以轻松轻松地完成,然后如果用户使用后退按钮,我希望后退按钮向后移动。目前 URL 发生变化,但框中的内容没有变化。我将如何改变或修复它?

4

2 回答 2

37

尝试以下操作:

<ul class="content_links">
    <li><a href="/historyapi/pages/content_page_1.html">Content page 1</a></li>
    <li><a href="/historyapi/pages/content_page_2.html">Content page 2</a></li>
    <li><a href="/historyapi/pages/content_page_3.html">Content page 3</a></li>
    <li><a href="/historyapi/pages/content_page_4.html">Content page 4</a></li>
    <li><a href="/historyapi/pages/content_page_5.html">Content page 5</a></li>
</ul>
<div id="content">
    <p>Content within this box is replaced with content from supporting pages using javascript and AJAX.
</div>

<script>
$(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);
        /* Instead of the line above, you could run the code below if the url returns the whole page instead of just the content (assuming it has a `#content`):
        $.get(State.url, function(response) {
            $('#content').html($(response).find('#content').html()); });
        */
        });


    // Capture all the links to push their url to the history stack and trigger the StateChange Event
    $('a').click(function(evt) {
        evt.preventDefault();
        History.pushState(null, $(this).text(), $(this).attr('href'));
    });
});
</script>
于 2012-11-25T16:44:24.083 回答
2

似乎以下位不起作用:

$.get(State.url, function(response) {
  $('#content').html($(response).find('#content').html());
});

您必须先将“响应”转换为 dom 元素,然后才能对其使用“查找”。像这样:

$.get(State.url, function(response) {
    var d = document.createElement('div');
    d.innerHTML = response;
    $('#content').html($(d).find('#content').html());
});
于 2014-12-15T13:13:27.160 回答