【问题标题】:Differentiate between back button pressed and forward button pressed with History API使用 History API 区分按下的后退按钮和按下的前进按钮
【发布时间】:2014-07-07 01:49:00
【问题描述】:

我正在使用历史 API 将新 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);
        });
    });
}

【问题讨论】:

标签: javascript html browser-history html5-history


【解决方案1】:

这是一种简化代码的方法:

您可以使用内置的<a> 标记和嵌套的<input> 标记来在页面之间导航。 Window.open() 将创建一个弹出窗口,window.location.replace() 将禁用历史 API,这两者都不会帮助您,因此嵌套的 <input> 标签(在 <a> 标签内)是最合乎逻辑的解决方案。

至于区分按钮,你可以在每个按钮中使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多