< form action ="1.asp" method ="post" name ="form1" onsubmit =“alert(‘执行了onsubmit事件’);return true;” >
< input type ="submit" name ="save" value ="保存" />
</ form >
但是如果我们直接调用form的submit()事件,却不会执行onsubmit(),代码如下:
< form action ="1.asp" method ="post" name ="form1" onsubmit =“alert(‘执行了onsubmit事件’);return true;” > ”>
< input type ="button" name ="save" value ="保存" onclick =”this.form.submit();” />
</ form >
我们如果想调用form的onsubmit事件只能通过调用,只有这样,才能执行这个事件:
< form action ="1.asp" method ="post" name ="form1" onsubmit =“alert(‘执行了onsubmit事件’);return true;” > ”>
< input type ="button" name ="save" value ="保存" onclick =”this.form.onsubmit();” />
</ form >
但是这样就失去了submit功效。也许我们可以用(attachEvent() / addEventListener() )模拟触发器的方式实现,语法如下(下面部分是转载内容……):
分析了一下原因:onsubmit属性的触发时机是在form用input:submit这样的button提交时才会触发,否则不会触发。
后来,在官方文档上也找到了如下说明,证明了我的这一分析,如下:
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.
为了证实这一分析,我做了一个完整的测试:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
< HTML >
< HEAD >
< script language ="javascript" >
function t(){
var f = document.getElementById( " f " );
f.submit();
alert( ' 333 ' );
}
</ script >
</ HEAD >
< BODY >
< form id ="f" onsubmit ="alert('2222');" >
< input type ="submit" value ="submit" />
< input type ="button" value ="button" onclick ="t();" />
</ form >
</ BODY >
</ HTML > 点击submit按钮即可出现“2222”提示,点击button的话,会出现“333”提示。
后来,在官方文档上也找到了如下说明,证明了我的这一分析,如下:
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.
为了证实这一分析,我做了一个完整的测试:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
< HTML >
< HEAD >
< script language ="javascript" >
function t(){
var f = document.getElementById( " f " );
f.submit();
alert( ' 333 ' );
}
</ script >
</ HEAD >
< BODY >
< form id ="f" onsubmit ="alert('2222');" >
< input type ="submit" value ="submit" />
< input type ="button" value ="button" onclick ="t();" />
</ form >
</ BODY >
</ HTML > 点击submit按钮即可出现“2222”提示,点击button的话,会出现“333”提示。