jQuery& history.js的例子

时间:2012-11-25 16:36:07

标签: jquery html5 history.js

我在使用jQuery的history.js时遇到了一些麻烦。我只是想使用后退按钮(他们似乎做得非常好)使导航设置工作。然而。当我点击后退按钮时,网址会更改为旧版(这又是好的和我想要的内容),但内容不会取代它。

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

    <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()很容易完成,然后我希望后退按钮在用户使用它时向后移动。目前网址已更改,但框中的内容未更改。我将如何改变或修复它?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:2)

似乎以下一点不起作用:

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

你必须转换回复&#39;进入dom元素之前,你可以使用&#39; find&#39;在上面。像这样:

$.get(State.url, function(response) {
    var d = document.createElement('div');
    d.innerHTML = response;
    $('#content').html($(d).find('#content').html());
});