2014-03-30 92 views
11

我正在使用jQuery動態加載div容器中的內容。history.pushstate失敗瀏覽器後退和前進按鈕

服務器端代碼檢測請求是否爲AJAX或GET。

我希望瀏覽器後退/前進按鈕與代碼一起工作,所以我嘗試使用history.pushState。我得下面這段代碼:

$('.ajax').on('click', function(e) { 
    e.preventDefault(); 
    $this = $(this); 
    $('#ajaxContent').fadeOut(function() { 
     $('.pageLoad').show(); 
     $('#ajaxContent').html(''); 
     $('#ajaxContent').load($this.attr('href'), function() { 
      window.history.pushState(null,"", $this.attr('href')); 
      $('.pageLoad').hide(); 
      $('#ajaxContent').fadeIn(); 
     }); 
    }); 
}); 

一切工作與瀏覽器的前進/後退按鍵,按計劃在酒吧的變化ADRESS但是頁面並沒有改變瀏覽時,除了罰款。我究竟做錯了什麼?

的幫助更新腳本克萊頓的回答

var fnLoadPage = function(url) { 
    $('#ajaxContent').fadeOut(function() { 
     $('.pageLoad').show(); 
     $('#ajaxContent').html('').load(url, function() { 
      $('.pageLoad').hide(); 
      $('#ajaxContent').fadeIn(); 
     }); 
    }); 
}; 

window.onpopstate = function(e) { 
    fnLoadPage.call(undefined, document.location.href); 
}; 

$(document).on('click', '.ajax', function(e) { 
    $this = $(this); 
    e.preventDefault(); 
    window.history.pushState({state: new Date().getTime()}, '', $this.attr('href')); 
    fnLoadPage.call(undefined, $this.attr('href')); 
}); 

回答

12

@ Barry_127,看看這是否會爲你工作:http://jsfiddle.net/SX4Qh/

$(document).ready(function(){ 
    window.onpopstate = function(event) { 
     alert('popstate fired'); 
     $('#ajaxContent').fadeOut(function() { 
      $('.pageLoad').show(); 
      $('#ajaxContent').html('') 
          .load($(this).attr('href'), function() { 
           $('.pageLoad').hide(); 
           $('#ajaxContent').fadeIn(); 
          }); 
     }); 
    }; 

    $('.ajax').on('click', function(event) { 
     event.preventDefault(); 
     alert('pushstate fired'); 
     window.history.pushState({state:'new'},'', $(this).attr('href')); 
    }); 

}); 

如果你看一看我提供的小提琴並點擊按鈕,警報將觸發,表明您正在推送新的狀態。如果你繼續點擊後退按鈕,那麼你會看到前一個頁面(或者popstate)會被觸發。

+0

Thnx很多克萊頓!你的例子非常具有說明性,它現在完全有意義。我會更新我的問題,以顯示我的最終代碼的樣子。 – Barry127