尝试这个简单的代码,我很惊讶它没有工作,我们开始吧:
<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>
代码只是应该在单击提交按钮时重定向到“test.html”,但它没有这样做。另一方面:alertIt() 工作正常...我的问题如下:将事件处理到表单中是否有一些我应该知道的特殊规则?
最佳答案
如果您不想提交表单,则需要返回 false。
function redirect(){
window.location.href = "test.html" ;
}
应该是
function redirect(){
window.location.href = "test.html" ;
return false;
}
您还应该 Hook submit
事件,最好不要 Hook click 事件,然后在处理程序中返回。
onclick="return redirect(); alertIt(); "
会工作(但不会提醒)
最佳情况下,您要做的是向表单(例如 myForm)添加一个 ID 并为其附加一个事件。
document.getElementById("myForm").addEventListener("submit",function(){
alertIt();
return redirect();
},false);
关于html - 使用 window.location.href 重定向表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679803/