使用历史记录API区分后退按钮和前进按钮的按下

15

我正在使用历史API在不重新加载页面的情况下向网页推送新URL。我有多个按钮,每个按钮都有不同的功能。

我的脚本现在几乎没有问题。当我按下按钮时,会发生某些事情,并且当我返回时,脚本会触发事件监听器而不重新加载页面。

然而,当我现在按前进按钮时,我想往前走。URL已正确更改为下一个URL,但事件监听器仍会触发,就像按下后退按钮一样。

示例:

  1. index1.html
  2. 按钮按下 → index2.html
  3. 按钮按下 → index3.html
  4. 后退按钮按下 → index2.html
  5. 前进按钮按下 → URL现在是index3.html,但内容是index1.html

我猜这是因为我有一个监听器,监听popstate,它会在按下后退按钮和前进按钮时触发。如何区分按下了哪种类型的按钮?

这是绑定监听器的部分:

if (window.history && window.history.pushState) {
    $(window).unbind('popstate');
    $(window).bind('popstate', function (e) {
        clearOverlays();
        var url = URL
        $.ajax ( {
            url : url
        }).done ( function ( data ) {
            console.log(data);
        });
    });
}

6
您不需要区分前进/后退。您应该使用“state”变量来存储用户导航到的状态。看起来您目前将其存储在全局变量“URL”中?附注:在现代版本的jQuery中,您应该使用“on”/“off”代替“bind”/“unbind”。 - CodingIntrigue
嗨,好的,我把我的绑定/解绑改成了开/关。那么,最好的方法是在popstate触发时获取URL,然后加载内容? - Musterknabe
7
在使用历史记录API时,URL有点无关紧要。它只是用于用户反馈,让他们知道自己在哪里。作为开发者,你应该专注于传递给pushState方法的state变量:history.pushState(**{ status: "OpenFile" }**, "Open", "irrelevanturl.html");。请注意,不要改变原来的意思。 - CodingIntrigue
4
如何在使用HTML5的pushstate时,区分popstate事件是由“后退”还是“前进”操作触发的?可能会涉及到相关讨论。 - Leonid Vasilev
显示剩余2条评论
1个回答

1
这里有一个简化代码的方法:
您可以使用内置的 <a> 标签和嵌套的 <input> 标签来在页面之间导航。 window.open() 会创建一个弹出窗口,而 window.location.replace() 则会禁用历史记录 API,两者都不会帮助您,因此在 <a> 标签中嵌套一个 <input> 标签是最合适的解决方案。
至于区分按钮,您可以在每个按钮中使用 HTML 的 onclick 属性来指定要执行的 JS 函数,在您的情况下是 window.history.back()window.history.forward()
例如,您可以使用以下内容。

<!DOCTYPE html>
<!-- Example of code for your first page -->
<html lang="en">

<head>
  <!-- Metadata -->
</head>

<body>
  <h1>Page 1.html</h1>
  <!-- The <a> tag below is what transitions between pages. The <input> tag is just for the appearance of a button. -->
  <a href="yourlink.html"><input type="button" value="page2"></a>
  <!-- Input tags below are required, unless you want to use 'javascript:(function)' in an <a> tag -->
  <input type="button" onclick="window.history.back()" value="Go back">
  <input type="button" onclick="window.history.forward()" value="Go forward">
</body>

</html>


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