Bar*_*127 13 javascript jquery browser-history pushstate
我正在使用jQuery动态加载div容器中的内容.
服务器端代码检测请求是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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
一切正常,除非使用浏览器后退/前进按钮浏览时,栏中的地址会根据计划更改,但页面不会更改.我究竟做错了什么?
在Clayton的回答帮助下更新了脚本
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'));
});
Run Code Online (Sandbox Code Playgroud)
Cla*_*ton 14
@ 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'));
});
});
Run Code Online (Sandbox Code Playgroud)
如果您查看我提供的小提琴并单击按钮,警报将会显示您正在推动新状态.如果您在触发状态触发后继续单击后退按钮,您将看到上一页(或popstate)将触发.
| 归档时间: |
|
| 查看次数: |
12255 次 |
| 最近记录: |