gpt4 book ai didi

javascript - 使用 History API 区分按下后退按钮和按下前进按钮

转载 作者:技术小花猫 更新时间:2023-10-29 12:21:39 35 4
gpt4 key购买 nike

我正在使用历史 API 将新 URL 推送到网页,而无需重新加载它。我有多个按钮,它们都有不同的功能。

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

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

例子:

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

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

这是绑定(bind)监听器的部分:

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);
});
});
}

最佳答案

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

您可以使用内置的 <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>

关于javascript - 使用 History API 区分按下后退按钮和按下前进按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23732026/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com