在为我正在创建的网站实施History.js时遇到了一些麻烦

时间:2016-09-30 17:41:12

标签: javascript jquery

我遇到了history.js作为我遇到的一些问题的可能解决方案。对于我正在构建的网站,我决定创建一个静态页面,我的内容将被加载到该页面中。所以我会有3个Div,(一个用于标题,一个用于菜单栏,一个用于内容)当单击菜单中的链接时,该页面将被加载到内容div中。因此,所有流量都保留在index.php页面中,因此单击后退按钮我会转到上次访问过的内容,但最后访问过的页面。我的理解是我可以用history.js解决这个问题。

所以在我的页面上,我在菜单栏中有几个链接,其中onclick一个函数被调用。例如

    <li><a href="javascript:void(0);" onclick="myprofile()" ><span>my profile</span></a></li>
    <li><a href="javascript:void(0);" onclick="mysettings()"><span>Settings<small> 

一个函数看起来像这样。

function myprofile() {
$('#content').load('members.php');
}
function mysettings() {
$('#content').load('settings.php');
}

我为history.js添加了一些javascript(在这个论坛上找到)虽然它确实改变了我的index.php中的url但是当点击它时它不会加载页面。当使用函数时,我如何让history.js工作? (我确实需要一些链接功能,所以只需将onload放在链接内就不是我的选择)

<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('onclick'));
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

History.pushState的第一个参数是&#34; data&#34;,其中包含其他信息。

因此,要保存历史记录条目,您可以在点击事件中执行此操作:

History.pushState({ href: 'members.php' }, $(this).text(), $(this).attr('onclick'));

然后在阅读它时你会在History.Adapter.bind函数中执行此操作:

$('#content').load(State.data.href);