This code works fine in FF, it takes the user back to the previous page, but not in Chrome:
<a href="www.mypage.com" onclick="javascript:history.go(-1)"> Link </a>
What's the fix?
您应该使用window.history
并返回false,以便浏览器不会导航href
(默认行为)。
<a href="www.mypage.com" onclick="window.history.go(-1); return false;"> Link </a>
使用下面的一个,它比history.go(-1)
更好。
<a href="#" onclick="location.href = document.referrer; return false;"> Go TO Previous Page</a>
Why not get rid of the inline javascript and do something like this instead?
Inline javascript is considered bad practice as it is outdated.
Notes
Why use addEventListener ?
addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling) It works on any DOM element, not just HTML elements.
<a id="back" href="www.mypage.com"> Link </a>
document.getElementById("back").addEventListener("click", window.history.back, false);
On jsfiddle
试试这个:
<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>
Try this dude,
<button onclick="goBack()">Go Back 2 Pages</button>
<script>
function goBack() {
window.history.go(-2);
}
</script>
It worked for me. No problems on using javascript:history.go(-1)
on Google Chrome .
javascript:history.go(-1)
on the enter URL space. 使用简单的这个行代码,不需要在href属性中放任何东西:
<a href="" onclick="window.history.go(-1)"> Go TO Previous Page</a>
Using a link with a URL to one page and having an on-click event that overrides it is not a good idea. What if the user opens the link in a new tab?
Consider:
<button id="back">Go back</button>
<script>
document.querySelector("#back").addEvenetListener("click", e => {
history.go(-1);
});
</script>
Or if you must use a link, at least:
<a href="javascript:history.go(-1)">Go back</a>
javascript:history.go(-1);
was used in the older browser.IE6 . For other browser compatibility try
window.history.go(-1);
where -1 represent the number of pages you want to go back (-1,-2...etc) and
return false
is required to prevent default event.
For example :
<a href="#" onclick="window.history.go(-1); return false;"> Link </a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.