jQuery和history.js的例子

Dav*_*vid 13 jquery html5 history.js

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

显然我想要的是页面内容加载到内容中,使用.load()很容易完成,然后我希望后退按钮在用户使用它时向后移动.目前网址已更改,但框中的内容未更改.我该如何改变或修复它?

sro*_*oes 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>
Run Code Online (Sandbox Code Playgroud)

  • @ user2035819是的,理想情况下,只有在ajax请求的情况下才能返回#content中的内容(您可以检查此服务器端).如果你无法控制返回的内容,你可以改变`$('#content').load(State.url);`到`$ .get(State.url,function(response){$('# content').html($(response).find('#content').html());});` (2认同)