2014-03-30 94 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