我正在使用 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();
});
});
});
一切正常,除了使用浏览器的后退/前进按钮浏览时,栏中的地址会按计划更改但页面不会更改。我做错了什么?
在 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'));
});
最佳答案
@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'));
});
});
如果您查看我提供的 fiddle 并单击按钮,将触发警报,表明您正在推送一个新状态。如果您在 pushstate 触发后继续单击后退按钮,您将看到前一个页面(或 popstate)将触发。
关于javascript - history.pushstate 使浏览器后退和前进按钮失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751023/