Curious redirection problem using location.href
I face a curious problem with redirection...
Look at this small example: it works only if I add the alert() call after the redirection sentence! If I remove the alert() it does not work anymore!!!
Any idea why (I'm using Firefox 3)?
Thanks.
<html>
<script type="text/javascript">
function GotoPage() {
location.href = "http://www.yahoo.com";
// Without this alert redirection does not work!!!
alert("Hello!");
}
</script&开发者_JS百科gt;
<body>
<form>
<button onclick="javascript:GotoPage()">Go</button>
</form>
</body>
</html>
Not sure, but I suppose that, if you don't return false
in your onclick
handler, the default action of the button is executed -- and that is not redirecting.
The alert freezes the browser long enough so the redirection is made before the control is given back to the default behavior of the button element.
Try using something like this :
<button onclick="GotoPage(); return false;">Go</button>
Or try modifying the function so it returns false
:
function GotoPage() {
location.href = "http://www.yahoo.com";
return false;
}
And return,in your onclick handler, what the function returned :
<button onclick="return GotoPage();">Go</button>
BTW : no need for the javascript:
part.
I believe you should set window.location, not location.href.
function GotoPage() {
window.location = "http://www.yahoo.com";
}
You should use window.location.assign instead of window.location.href
Once, I used the function like yours without the alert statement, and when I tried it on FireFox, it wouldn't work. After that, I used function assign() instead of assigning the href property and it worked well for me.
精彩评论