2013-04-12 46 views
0

這是我的代碼來改變其工作history.pushState(),然後單擊後退/前進按鈕

$.ajax({ 
    url: url, 
    success: function (data) { 
    $(selector).html(data); 
    var title = data.match("<title>(.*?)</title>")[1]; // get title of loaded content 
    window.history.pushState({page : 0} , document.title, window.location.href); // store current url.  
    window.history.pushState({page : 1} , title, url); // Change url. 
    document.title = title; // Since title is not changing with window.history.pushState(), 
    //manually change title. Possible bug with browsers. 
    window.onpopstate = function (e) { 
     window.history.go(0); 
    }; 
    } 
}); 

AJAX負載URL當我點擊,以前的頁面加載。如果我再次點擊什麼都沒有發生。再一次點擊它將轉到第一頁。一些測試後我發現,也有後退按鈕2相同的頁面,在每個AJAX加載

enter image description here

此外,我需要一個代碼來獲得歷史時,點擊前進按鈕

回答

1

版主刪除了我後,因爲我真的給了一小段代碼試圖幫助。


但我依然會盡量舉一個例子:

假設你有這樣的代碼是由事件觸發的onclick。

$(function() { 
    function load(url, push) { 
     $.ajax({ 
      url: url, 
      success: function (data) { 
       var title = data.match("<title>(.*?)</title>")[1]; 
       document.title = title; 
       if (push) { 
        history.pushState(null, title, url); 
       } 
      } 
     }); 
    } 

    $(document).click(function(e) { 
     if (e.target.nodeName === 'A') { 
      var url = $(e.target).attr('href'); 
      if (url.indexOf('#') !== 0) { 
       load(url, true); 
       e.preventDefault(); 
      } 
     } 
    }); 

    $(window).bind('popstate', function(e) { 
     load(window.location.href, false); 
    }); 
});