javascript history.pushstate 使浏览器的后退和前进按钮失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22751023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
history.pushstate fails browser back and forward button
提问by Barry127
I'm using jQuery to dynamically load content in a div container.
我正在使用 jQuery 在 div 容器中动态加载内容。
The server side code detects if the request is AJAX or GET.
服务器端代码检测请求是 AJAX 还是 GET。
I want the browsers back/forward buttons to work with the code so I try to use history.pushState. I've got to following piece of code:
我希望浏览器的后退/前进按钮与代码一起工作,所以我尝试使用 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();
});
});
});
Everything works fine except when browsing with the browsers back/forward button, the adress in the bar changes according to plan but the page doesn't change. What am I doing wrong?
一切正常,除了使用浏览器后退/前进按钮浏览时,栏中的地址按计划更改但页面不会更改。我究竟做错了什么?
Updated script with the help from Clayton's answer
在克莱顿的回答的帮助下更新了脚本
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'));
});
回答by Clayton
@Barry_127, see if this will work for you: http://jsfiddle.net/SX4Qh/
@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'));
});
});
If you take a look at the fiddle I provided and click the button, the alert will fire showing that you are pushing a new state. If you then proceed to click the back button once the pushstate has fired, you will see that the previous page (or popstate) will fire.
如果您查看我提供的小提琴并单击按钮,则会触发警报,表明您正在推送新状态。如果在 pushstate 触发后继续单击后退按钮,您将看到前一页(或 popstate)将被触发。