返回按钮只能使用一次

4

我正在制作网页,但找不到解决问题的答案。

我正在使用window.history.pushstate和onpopstate事件,这是我的代码:

changeContent = function(href) {
  window.history.pushState({}, '', href);
  if (href == "/") {
    $('#main').load('main.html');
  } else {
    $('#main').html('<iframe id="gallery" src="photos'+href+'/index.html"></iframe>');
  }
};

$(window).on("popstate", function(e) {
  changeContent(location.pathname);
});

$(document).on("click", ".galleryLink", function() {
  var href = $( this ).attr( "href" );
  changeContent(href)
  return false;
});

即:谷歌页面 -> 我的主页 -> 图库 -> 返回按钮 -> 我的主页 -> 返回按钮 -> 我的主页 -> 返回按钮 -> 我的主页。
发生了什么?
2个回答

5

明白了!

行:

window.history.pushState({}, '', href);

应该在内部

$(document).on("click", ".galleryLink", function()

我把它放在里面。
changeContent = function(href)

这是我的错... :-)



我没有使用 JQuery 但是遇到了相同的问题。我无法将一个函数作为第三个参数,你是如何解决这个问题的? - Roberto

1
这里说,jQuery在捕获popstate事件时存在问题,应该使用原生的onpopstate。但我想知道为什么它能够工作一次?

jQuery绑定popstate事件未通过


我的 jQuery 捕获工作得很好,我找到了答案,但现在无法回答自己的问题(声望太低)。 - user3251085
@YaPKnn 哦,是的,终于搞定了,changecontent 在 popstate 时也会被调用。 - loveNoHate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接