【发布时间】:2016-12-31 20:42:18
【问题描述】:
我有 3 个相关问题要问
问题 1
在window.addEventListener('popstate', function(e) 上,我如何知道按下的按钮是forward() 还是back() 按钮。例如
window.addEventListener('popstate', function(e){
var buttonDirection = // the button that was clicked
if(buttonDirection == history.back()){
// blah blah blah
} else if(buttonDirection == history.forward()){
// blah blah blah
}
})
问题 2
我想在ajax 成功后pushState 以更改页面内容所以我这样做了,我真的不知道这是不是最好的方法
$.ajax({
url: 'path.php',
success: function(data){
$('html').html(data);
history.pushState('', '', 'path.php');
var pushed = 'yes';
}
})
现在问题出现在ajax 成功和pushed = yes 之后,然后我想在单击后退按钮以检索上一页内容时监听事件,因为在history.pushState 之后forward() 按钮是禁用,所以我这样做了
window.addEventListener('popstate', function(e){
if(pushed == 'yes'){
// run code to restore back previous page content
$.ajax({
url: 'current_page.php',
success: function(data) {
$('html').html(data);
pushed = 'yesBack';
}
});
}
// now I want to run another code to replace the page content again if the forward button is clicked and pushed is == yesBack
// that's where my reason for question 1 come out
// so how do I know if the button that was clicked is the forward
})
最后一个问题
如果您在移动浏览器上研究 Facebook,您会发现:
- 如果您在个人资料图片相册页面上单击照片,则会触发
history.pushState并使用ajax请求更改页面内容,现在将显示您单击的图像。 - 如果单击返回按钮,
ajax请求将再次用于检索上一页内容。 - 如果您再次单击前进按钮,则再次使用
ajax请求来更改页面内容以再次显示图像。 - 如果您现在通过单击下一个或上一个链接继续滚动图像,并且再次触发
history.pushState并使用ajax请求检索新图像,无论您滚动了多少图像,如果您再次单击返回按钮,则会返回到第一页,即个人资料图片相册页面。 - 如果您随后再次单击前进按钮,则会将您带到您在单击后退按钮之前离开的页面。
现在我的第三个问题是如何在我自己的网页中实现所有这些观察。
我尝试查看 Facebook 源代码,但无法理解或找不到触发 history.pushState 的任何地方。请任何人回答我列出的任何问题或我可以阅读以获得答案的文档
【问题讨论】:
标签: browser-history html5-history