在处理表单提交的时候遇到一个问题,通常用<input type="submit" value="提交" />按钮来提交form,再监听form的onsubmit事件就能在前端处理表单验证的事情。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="form" action="http://www.a.com" method="post">
<input type="submit" value="提交" />
</form> <script>
var form =document.getElementById("form");
form.onsubmit = function(){
alert("表单提交了")
}
</script>
</body>
</html>

以上代码很顺利,没有任何问题。

当用别的元素来触发form的提交时确不会触发onsubmit事件。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="form" action="http://www.a.com" method="post">
<input type="submit" value="提交" />
</form>
<a href="javascript:void(0)" id="txtBtn">提交</a>
<script>
var form =document.getElementById("form"),
txtBtn = document.getElementById("txtBtn"); txtBtn.onclick = function(){
form.submit();
}
form.onsubmit = function(){
alert("表单提交了")
}
</script>
</body>
</html>

当点击a链接的提交时以为会弹出:表单提交了,可是没有,但表单内容是提交了的,但没有触发onsubmit事件。查了下手册,原文如下:

The submit method does not invoke the onsubmit event handler. Call the onsubmit event handler directly. When using Microsoft® Internet Explorer 5.5 and later, you can call the fireEvent method with a value of onsubmit in the sEvent parameter. 

关于fireEvent的介绍,可以看这里:http://msdn.microsoft.com/en-us/library/ms536423(v=vs.85).aspx

于是加上fireEvent。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="form" action="http://www.a.com" method="post">
<input type="submit" value="提交" />
</form>
<a href="javascript:void(0)" id="txtBtn">提交</a>
<script>
var form =document.getElementById("form"),
txtBtn = document.getElementById("txtBtn"); txtBtn.onclick = function(){
form.fireEvent('onsubmit');
form.submit();
} form.onsubmit = function(){
alert("表单提交了")
} </script>
</body>
</html>

以上代码如愿的弹出:表单提交了,用a标签提交也能触发onsubmit事件了。

到此为止以为OK了,可是在chrome和firefox下依然不行。百度GOOGLE一翻,找到了解决方法,直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="form" action="http://www.a.com" method="post">
<input type="submit" value="提交" />
</form>
<a href="javascript:void(0)" id="txtBtn">提交</a>
<script>
var form =document.getElementById("form"),
txtBtn = document.getElementById("txtBtn"); txtBtn.onclick = function(){
var result;
if(form.fireEvent){
//IE浏览器
result=form.fireEvent('onsubmit');
}else{
//FIREFOX\CHROME等标准浏览器
var evt = document.createEvent('HTMLEvents');
evt.initEvent('submit',false,true);
result=form.dispatchEvent(evt);
}
if(result){
form.submit();
} } form.onsubmit = function(){
alert("表单提交了")
} </script>
</body>
</html>

完美解决问题,各浏览器下表现一致了!

关于firefox,chrome等标准浏览器的实现中所用到的方法,具体描述看下面几个链接:

http://www.w3school.com.cn/xmldom/met_document_createevent.asp

http://www.w3school.com.cn/xmldom/met_element_dispatchevent.asp

http://www.w3school.com.cn/jsref/event_initevent.asp

05-04 01:39