2013-05-17 58 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可能對我所需要的來說太大 - 我所有的ajax都在工作,只是那些討厭的後退/前進按鈕。 – CHarris