Mus*_*abe 15 html javascript html5 browser-history html5-history
我正在使用历史API将新URL推送到网页而不重新加载它.我有多个按钮,都有不同的功能.
我的脚本现在几乎没有问题.当我按下按钮时会发生一些事情,当我返回时,脚本会触发事件监听器而不重新加载页面.
但是,当我现在按下前进按钮时,我想继续前进.URL已正确更改为下一个,但事件侦听器仍然会像按下后退按钮一样触发
例:
index1.htmlindex2.htmlindex3.htmlindex2.htmlindex3.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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
这是简化代码的一种方法:
您可以将内置<a>标签与嵌套<input>标签一起使用,以便在页面之间导航。Window.open()将创建一个弹出窗口,并将window.location.replace()禁用历史 API,这两者都对您没有帮助,因此嵌套<input>标签(标签内部<a>)是最合乎逻辑的解决方案。
至于区分按钮,您可以使用onclick每个按钮中的 HTML 属性来指定要执行的 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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2699 次 |
| 最近记录: |