Html 使用 window.location.href 重定向表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16679803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect on form's submission with window.location.href
提问by Akheloes
Trying out this simple code, I am amazed it didn't work, here we go :
尝试这个简单的代码,我很惊讶它不起作用,我们开始吧:
<form method="get" action="" >
<input type="submit" value="validate" onclick="redirect(); alertIt(); "/>
</form>
<script>
function redirect(){
window.location.href = "test.html" ;
}
</script>
<script>
function alertIt(){
alert("redirect");
}
</script>
The code is just supposed to redirect to "test.html" on click of the submit button, which it fails to do. On the other hand : alertIt() works fine... My question is the following : does event handeling into a form have some special rules I should know about ?
该代码只是应该在单击提交按钮时重定向到“test.html”,但它没有这样做。另一方面:alertIt() 工作正常...我的问题如下:将事件处理到表单中是否有一些我应该知道的特殊规则?
回答by Benjamin Gruenbaum
You need to return false if you want the form not to submit anyway.
如果您希望表单无论如何都不要提交,则需要返回 false。
function redirect(){
window.location.href = "test.html" ;
}
Should be
应该
function redirect(){
window.location.href = "test.html" ;
return false;
}
You should also hook on the submit
event and not the click event preferably, and return in the handler.
您还应该挂钩submit
事件而不是点击事件,并在处理程序中返回。
onclick="return redirect(); alertIt(); "
Would work (but not alert)
会工作(但不警觉)
Optimally, what you'd want to do is add an id to the form for example myForm and attach an event to it.
最理想的是,您想要做的是向表单添加一个 id,例如 myForm 并为其附加一个事件。
document.getElementById("myForm").addEventListener("submit",function(){
alertIt();
return redirect();
},false);
回答by Josefh luis
You can use location.replace()
too. Following link explains JavaScript location with working example.
你也可以使用location.replace()
。以下链接通过工作示例解释了 JavaScript 位置。
may help you.
可能会帮助你。