微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery&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>

显然,我想要的是将页面内容加载到使用.load()完成的内容中,然后如果用户使用它,我希望后退按钮向后移动.此时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>

<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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


jQuery表单验证提交:前台验证一(图文+视频)
jQuery表单验证提交:前台验证二(图文+视频)
jQuery如何实时监听获取input输入框的值
JQuery怎么判断元素是否存在
jQuery如何实现定时重定向
jquery如何获取复选框选中的值
jQuery如何清空form表单数据
jQuery怎么删除元素节点
JQuery怎么循环输出数组元素
jquery怎么实现点击刷新当前页面