31

クロスブラウザ方式でjQueryとAJAXを使用してナビゲーション履歴を実装したいと思います。私のアプローチは、をサポートしていないブラウザでwindow.history.pushStateハッシュURLを使用してフォールバックすることです。/#!/urlwindow.history.pushState

例えば:

<a href="/home">home</a>
<a href="/about">about</a>
<a href="/contact">contact</a>

をサポートするブラウザでwindow.history.pushStateは、これらのリンクのいずれかをクリックすると、ページを更新せずにアドレスをhttp://domain.com/home、http://domain.com/aboutな​​どに変更する必要がありますブラウザがサポートしない場合はwindow.history.pushState、を使用する必要があります。フラグメント識別子、つまり:http ://domain.com/#!/home 、http ://domain.com/#!/about 。


更新:ここでのフィードバックに基づいて、古いブラウザーのフォールバックでHTML5 HistoryAPIのjQueryアドレスを使用するAjaxSEOgit)を 実装しました。/#!/url

4

3 に答える 3

22
// Assuming the path is retreived and stored in a variable 'path'

if (typeof(window.history.pushState) == 'function') {
    window.history.pushState(null, path, path);
} else {
    window.location.hash = '#!' + path;
}
于 2010-11-22T22:36:48.360 に答える
6

フォールバック ハッシュ URL で使用しているもの:

History = History || {};
History.pathname = null;
History.previousHash = null;
History.hashCheckInterval = -1;
History.stack = [];
History.initialize = function () {
    if (History.supportsHistoryPushState()) {
        History.pathname = document.location.pathname;
        $(window).bind("popstate", History.onHistoryChanged);
    } else {
        History.hashCheckInterval = setInterval(History.onCheckHash, 200);
    }
};
History.supportsHistoryPushState = function () {
    return ("pushState" in window.history) && window.history.pushState !== null;
};
History.onCheckHash = function () {
    if (document.location.hash !== History.previousHash) {
        History.navigateToPath(document.location.hash.slice(1));
        History.previousHash = document.location.hash;
    }
};
History.pushState = function (url) {
    if (History.supportsHistoryPushState()) {
        window.history.pushState("", "", url);
    } else {
        History.previousHash = url;
        document.location.hash = url;
    }
    History.stack.push(url);
};
History.onHistoryChanged = function (event) {
    if (History.supportsHistoryPushState()) {
        if(History.pathname != document.location.pathname){
            History.pathname = null;
            History.navigateToPath(document.location.pathname);
        }
    }
};
History.navigateToPath = function(pathname) {
    History.pushState(pathname);

    // DO SOME HANDLING OF YOUR PATH HERE

};

次のようにして、クリックイベントをこれにバインドできます。

$(function(){
    $("a").click(function(){
        var href = $(this).attr('href');
        History.navigateToPath( href )
        return false;
    });
});

この例についてさらに説明が必要な場合は、喜んでお聞きします。


編集

私の他の答えを見てください。

于 2011-05-06T12:33:16.023 に答える