【问题标题】:Prevent multiple clicks back navigation on refreshed page防止在刷新页面上多次点击返回导航
【发布时间】:2018-07-02 14:40:41
【问题描述】:

我已经使用有效的 window.history.go() 方法转到上一页按钮。

问题:页面重新加载后,我需要多次单击按钮才能转到上一页。

那么如何防止多次点击返回按钮返回第一次点击呢?

history.pushState()window.onpopevent() 方法找到这篇文章:https://www.safaribooksonline.com/library/view/javascript-cookbook/9781449390211/ch20s04.html,这可以解决吗?

以及如何在我的代码中实现?

代码

HTML:

<div id="goToPreviousPage">
   <a href="#"></a>
</div>

JS:

const goBackButton = document.querySelector("#goToPreviousPage");

goBackButton.onclick = function(e) {
   window.history.go(-2);
}

使用window.onbeforeunload 方法返回按钮在重新加载页面后起作用,但在正常状态下不重新加载页面返回按钮无法再导航:

goBackButton.onclick = function(e) {
   window.onbeforeunload = function(event)
      {
        return confirm("Confirm refresh");
      }; 
   window.history.go(-4);
}

有什么建议吗?

【问题讨论】:

  • 您不想让按钮点击多次吗?
  • 不,我需要在页面重新加载后一键执行 window.history.go(-1) 方法,但是在单击 3 次后它可以工作然后我刷新页面
  • 您要导航到的 URL 是什么样的?我会考虑在查询字符串或隐藏字段中保存/保留“previousURL”,然后单击按钮加载上一页。有什么原因你不能正常加载页面?
  • 在页面重新加载后 URL 不再只是页面标题然后导航。

标签: javascript html ajax html5-history


【解决方案1】:

我认为问题在于您的 href="#" 在单击时将当前页面添加到历史记录中。尝试将以下内容添加到您的函数中以防止链接的默认行为。

e.preventDefault()

【讨论】:

  • 由于您将 onclick 绑定到 div,您可以尝试删除链接吗?
  • 换了个link标签换了div还是一样的问题
  • 你也可以试试 window.histroy.go(document.referrer);
  • 好建议,但使用 document.refferer 我无法导航到上一页,只是在单击后重新加载页面,在我的情况下唯一可行的方法是 window.history.go(-2)跨度>
猜你喜欢
  • 2021-12-03
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 2017-04-17
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多