Javascript: window.location.href doesn't redirect when calling function within a function
window.location.href redirects the browser to stackoverflow.com when the button is clicked, but does not when hitting "Enter" in the input textfield, despite both event listeners using the same function visitStack.
If this helps, changing the form tags to div tags somehow makes it work, but it's not semantic, of course.
Changing "keydown" in the last line to "click", and moving visitStack(e) immediately within keyDownTextField(e), make it work too.
So keydown and/or form tags seem to be the culprits here, but I'm not sure.
<form>
<input id="iamtext" type="text" />
<input id="gobutton" type="button" value="Overflow" /> 开发者_开发问答
</form>
<script type="text/javascript">
document.getElementById("gobutton").addEventListener("click", visitStack, false);
function visitStack(e) {
e.stopPropagation();
window.location.href = "http://www.stackoverflow.com";
}
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("Entered!");
visitStack(e);
}
}
document.getElementById("iamtext").addEventListener("keydown", keyDownTextField, false);
</script>
Hitting ENTER
in a text input field in an HTML form has rather different effects on different browsers.
In your case, I assume that the form is submitted on hitting ENTER. Since you haven't specified any action
, the form is submitted to same page leading to a reload.
You could also try adding e.preventDefault()
as well as e.stopPropagation()
to visitStack().
精彩评论