Creating a back link

时间:2015-06-15 14:47:33

标签: javascript

I need to create a back link. I was adviced to use this to do it:

<a href="#" onclick="javascript:window.history.back();">Back</a>

But it works only in IE and Mozilla, but not in Safari, Google Chrome and Opera. How to fix it?

2 个答案:

答案 0 :(得分:3)

You're blocking the redirection using the href,

replace

<a href = "#" onclick="javascript:window.history.back();">Back</a>

with

<a onclick="window.history.back();">Back</a><--!javascript: is not required-->

or

Add a return false; to it.

<a href="#" onclick="window.history.back();return false;">Back</a>

答案 1 :(得分:3)

The problem of your code is the onclick's value. The "protocol" javascript: is only required if you use JavaScript code within the href attribute. This signals your browser that the protocol of the link is not http: or https: but javascript:.

If you use the onclick attribute, the browser already knows that the value will be JavaScript, because all attributes like onclick, onfocus, onchange, ... require JavaScript as it's value.

This will work:

<a href="#" onclick="window.history.back(); return false;">Back</a>

Adding return false; as a second command will prevent the site from jumping to the top, but that's not required.

相关问题