I am trying to make this work

<script>
document.write('<button onclick="location.href=' + document.referrer + '">Go back</button>');
</script>

It should be nothing but a simple "Back" button to the previsous page. When I do it like an "a href" it works

<script>
    document.write('<a href="' + document.referrer + '">Go back</a>');
</script>

but when trying tom ake it as a "button" it fails. The button is there but didnt navigate to the previsious page

有帮助吗?

解决方案 2

You could also implement native back with:

window.history.back();
//in your onclick="history.back()"
//also can try with:
//javascript:history.go(-1)">

Or call a function that check if history.back() is available in the browser first else implement a custom back function/code as is showed here (I would prefer take out the code from the html just handle the onclick in my function)

Using javascript history.back() fails in Safari .. how do I make it cross-browser?

For a robust solution check history.js:

https://github.com/browserstate/history.js

其他提示

Add another escaped quote into the href body (as well as a semicolon at the end, although I don't know if that would make a difference) and see if that works...

<script>
document.write('<button onclick="location.href=\'' + document.referrer + '\';">Go back</button>');
</script>

You're missing the quotes around the URL in the href, so try escaping it like this (worked for me)

document.write('<button onclick="location.href=\'' + document.referrer + '\'">Go back</button>');

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top