我不明白为什么在 Firefox 中,window.history.back()
确实适用于按钮:
<button onclick="window.history.back()">Go back</button>
但它不适用于链接:
<a onclick="window.history.back()">Go back</a>
有什么区别?
举例说明:
index.html
<!DOCTYPE html>
<html>
<body>
<h1>First page</h1>
<br/>
<a href="second.html">Second</a>
</body>
</html>
second.html
<!DOCTYPE html>
<html>
<body>
<h1>Second page</h1>
<a href="third.html">Third</a>
<br/>
<br/>
<button onclick="window.history.back()">Go Back (button)</button>
<br/>
<a href="javascript: void(0);" onclick="window.history.back()">Go Back (a)</a>
</body>
</html>
third.html
<!DOCTYPE html>
<html>
<body>
<h1>Third page</h1>
<br/>
<button onclick="window.history.back()">Go Back (button)</button>
<br/>
<a href="javascript: void(0);" onclick="window.history.back()">Go Back (a)</a>
</body>
</html>
场景:
- 运行 index.html 并点击第二。
- 在 second.html 上点击Third。
- 在 third.html 上点击返回 (a)。
- 在 second.html 上单击返回 (a)。繁荣!我在 third.html 上,而不是在 first.html 上!!!
Plunker example (注意!在 Firefox 上运行它)
如果您使用返回(按钮),它会起作用。 <a onclick
有什么区别?和 <button onclick
在这种情况下?
最佳答案
您遇到这个问题 ( quoted from vikku.info ):
But what had happened when i press the back button after navigating to various pages was i got locked between the last two navigated pages.
评论中有人一针见血地指出了这个问题。
- 当您创建
onclick
属性时,您将附加一个用于单击链接的附加事件处理程序。但是,浏览器仍会处理一些 native 逻辑,因此它仍会将当前页面添加到历史记录中; - 当您将特定的 javascript 传递到
href
属性时,您实际上是在覆盖浏览器的 native 逻辑,因此它不会将当前页面添加到历史;
简单、肮脏的解决方案
HTML:
<a href="javascript:window.history.back();">Back</a>
改进的解决方案
我还创建了一个使用 native preventDefault
功能 ( Plunker example ) 的示例 ( MDN on preventDefault )。在这种情况下,不需要在 href
属性中编写 javascript。现在,您可以通过链接到主页等方式支持不使用 javascript 的用户。您最好也避免使用内联事件处理程序。
HTML:
<a href="index.html" id="backButton">Back</a>
Javascript:
var backbutton = document.getElementById("backButton");
backbutton.onclick = function(e){
e = e || window.event; // support for IE8 and lower
e.preventDefault(); // stop browser from doing native logic
window.history.back();
}
关于javascript - 为什么 history back 在 Firefox 中的 <a> onclick 上不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20420717/