onclick=“[removed]history.go(-1)” not working in C

2019-01-31 08:32发布

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?

8条回答
forever°为你锁心
2楼-- · 2019-01-31 09:16

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>   
查看更多
放我归山
3楼-- · 2019-01-31 09:21

Try this dude,

<button onclick="goBack()">Go Back 2 Pages</button>
<script>
  function goBack() {
    window.history.go(-2);
  }
</script>
查看更多
放我归山
4楼-- · 2019-01-31 09:25

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>
查看更多
唯我独甜
5楼-- · 2019-01-31 09:31

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

查看更多
Root(大扎)
6楼-- · 2019-01-31 09:32

Use the below one, it's way better than the history.go(-1).

<a href="#" onclick="location.href = document.referrer; return false;"> Go TO Previous Page</a>
查看更多
Emotional °昔
7楼-- · 2019-01-31 09:36

You should use window.history and return a false so that the href is not navigated by the browser ( the default behavior ).

<a href="www.mypage.com" onclick="window.history.go(-1); return false;"> Link </a>
查看更多
登录 后发表回答