2013-05-17 8 views
6

私は慎重に変更したコードのおかげで、私のサイトははるかに早く動いていますが、ブラウザの「戻る/進む」ボタンがうまくいけば大好きです。今、下のコードでは、ブラウザのアドレスバーは決して変更されません。誰かが「戻る」をクリックすると、それらはアプリケーションから取り除かれます。バックとフォワードのボタンをAjaxと連携させる

ブラウザの戻る/進むボタンが機能するようにこれを簡単に変更できますか?それとも、誰かが私を正しい方向に向けることができるかどうか。助けてくれてありがとう。

$(document).on("ready", function() { 

    //I want to load content into the '.page-content' class, with ajax 

    var ajax_loaded = (function (response) { 

     $(".page-content") 

     .html($(response).filter(".page-content")); 

     $(".page-content .ajax").on("click", ajax_load); 


    }); 



    //the function below is called by links that are described 
    //with the class 'ajax', or are in the div 'menu' 

    var history = []; 

    var ajax_load = (function (e) { 

     e.preventDefault(); 


     history.push(this); 
     var url = $(this).attr("href"); 
     var method = $(this).attr("data-method"); 


     $.ajax({ 
      url: url, 
      type: method, 
      success: ajax_loaded 
     }); 

    }); 


    //monitor for clicks from menu div, or with 
    //the ajax class 
    //why the trigger? 

    $("#menu a").on("click", ajax_load); 
    $(".ajax").on("click", ajax_load); 
    $("#menu a.main").trigger("click"); 



}); 
+0

はい。 History.js - ブラウザの状態をプッシュし、前後の動きを許可します –

答えて

1

ここにあなたが求めているものを検出する方法があります。

バックとフォワードボタンで遊ぶのは危険です。

window.onload = function() { 

    if (typeof history.pushState === "function") { 

     history.pushState("someState", null, null); 

     window.onpopstate = function() { 

      history.pushState("newState", null, null); 

      // Handle the back (or forward) buttons here 
      // Will not handle refresh, use onbeforeunload for this. 
     }; 
    } 
} 
+0

面白いですが、実装方法は不明です。確かにコメントされた '//バック(またはフォワード)ボタンをここで処理する'は、私が探しているコードですか? 「バックとフォワードボタンを使って遊ぶことでベアが危険な仕事です」とはどういう意味ですか?ありがとう。 – CHarris

0

あなたは間違いなくここにいくつかのサンプルコードです​​3210 をチェックする必要があります: -

(function(window,undefined){ 

    // 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(); // Note: We are using History.getState() instead of event.state 
     //History.log(State.data, State.title, State.url); 
     var goto_url = State.url;    
     $.ajax({ 
      url: goto_url, 
      dataType: "script" 
     }); 
    }); 
    })(window); 
1

あなたはjqueryのアドレスプラグイン(http://www.asual.com/jquery/address/)を使用することができますが。 ユーザーが[戻る/進む]ボタンを押したときを検出するイベントがあります。

$.address.externalChange(function() { console.log('back/forward pressed'); }); 

私が知る限り、前と後を区別する方法はありません。

+0

乾杯、それをチェックします。私はhistory.jsが私が必要とするものには余りにも広すぎるかもしれないと思う - 私のすべてのアヤックスはうまくいき、厄介なバック/フォワードボタン。 – CHarris

関連する問題