History.pushState 浏览器后退和前进按钮失败
history.pushstate fails browser back and forward button
我正在使用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();
});
});
});
一切正常,除了使用浏览器后退/前进按钮浏览时,栏中的地址会根据计划更改,但页面不会更改。我做错了什么?
在克莱顿的回答的帮助下更新了脚本
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'));
});
});
如果您查看我提供的小提琴并单击按钮,则会触发警报,表明您正在推动一个新状态。如果在 pushstate 触发后继续单击后退按钮,您将看到上一页(或 popstate)将触发。
相关文章:
- jQuery分页下一页和上一页按钮在点击零或超过最后一页后失败
- 验证失败时禁用按钮
- 后退按钮在 window.location.replace(href);之后失败
- 删除带有按钮的输入表单失败
- 我用脚本创建了一个按钮.我可以通过点击按钮调用其他函数吗?我这样做,但失败了
- js角度按钮保持循环失败
- 返回按钮回调函数在特定情况下失败或未启动
- 在Firefox中,当type=submit for按钮时,请求服务器失败
- 为什么提交按钮在 extjs 中仍然有效,即使使用 vtype 的电子邮件验证失败
- 单选按钮检查属性在函数 - JavaScript 中失败
- 按钮单击Javascript函数失败,但函数有效
- 单击按钮时加载 jqGrid,但第二次失败
- 使用单选按钮切换面板失败
- 为什么我的Knockout Radio按钮在使用单击绑定的另一个元素内时会失败
- 当第三方cookie被禁止时,任何优雅地捕捉失败的类似facebook的按钮的想法
- 如果表单提交失败,请启用提交按钮
- 为什么JQuery NOT选择器在类型提交时失败,但在类型按钮上有效
- 当我传递参数时,从动态添加的html按钮调用javascript函数失败
- 向数据表单元格插入按钮失败
- History.pushState 浏览器后退和前进按钮失败