AnA*_*ice 29 javascript jquery html5 history
鉴于以下内容:
$(window).bind("popstate", function() {
alert('popstate');
});
Run Code Online (Sandbox Code Playgroud)
首次加载时,警报会触发FireFox和Chrome,但不会触发Safari.这是为什么?其他人看过这个并知道如何最好地解决这个问题?
Nob*_*obu 45
请参阅pjax中的代码.pjax现在是相当流行的开源库,所以下面的逻辑可能是最好的避免这个问题.
var popped = ('state' in window.history), initialURL = location.href
$(window).bind('popstate', function(event) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL
popped = true
if ( initialPop ) return
...
Run Code Online (Sandbox Code Playgroud)
https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js
小智 17
在webkit中,popstate事件在页面加载时触发.为了避免这种情况,这个简单的工作对我有用:
每次我开火history.push(...)我都会将历史class 记录添加到body-tag:
history.push(...);
$("body").addClass("historypushed");
Run Code Online (Sandbox Code Playgroud)
当我触发popstate事件时,我会检查这个类:
$(window).bind('popstate', function(e) {
if($("body").hasClass("historypushed")) {
/* my code */
}
});
Run Code Online (Sandbox Code Playgroud)
Tam*_*lyn 15
现在情况正好相反.Chrome修复了该错误,现在在页面加载时触发popstate,但Firefox 4(自RC以来)已经偏离规范,现在不会激活popstate!
更新:HTML5规范在2011年更改为状态popstate不应在页面加载时触发.从Firefox 4和Chrome 34开始, Firefox和Chrome现在都做对了.