表單Form的submit事件不響應

一、問題描述

    當用JS調用form的方法submit直接提交form的時候,submit事件不響應。爲什麼?知道的請回復。類比一下,我用input.select()做了測試,卻能響應select事件。這個原因先放一邊,我們看看先怎麼把眼下的問題解決了。
不響應事件的代碼示例:

 <form id="form1" action="http://www.webjxcom"></form>
<script type="text/javascript">
 var form = document.getElementById(’form1’);
 form.onsubmit = function() {
  alert(1);
 };
 form.submit();
</script>

    實際運行,不會有alert出來。
    雖然用submit方法來提交表單有違Unobtrustive Javascript的原則,但有時候不得不用,比如做搜索提示(auto-complete)選中Item之後就需要用JS來提交搜索表單。

    二、問題分析

    既然本身不響應事件,那只有手工觸發這些事件了,確定手工觸發方案之前先回顧一下事件的註冊方式:
    “原始”的註冊方式有兩種,看代碼示例:

 <form id="form1" action="http://www.webjx.com/" onsubmit="alert(1)"></form><form id="form1" action="http://www.webjx.com"></form>
<script type="text/javascript">
document.getElementById(’form1’).onsubmit = function() {
 alert(1);
}
</script>

    這樣的註冊事件,會給form增加了一個方法onsubmit。所以,可以通過直接執行這個方法,等同於手工觸發了事件。
看代碼示例:

 <script type="text/javascript">
 form.onsubmit();
</script>

    這樣可以得到一個alert。

    但是在如今“先進”的DOM2標準註冊方式以及IE的註冊方式attachEvent已經很常用。這些註冊方式,onsubmit方法是不存在的,如果使用form.onsubmit()會直接報錯。

    三、解決方案

    當然“先進”的註冊方式本身也提供了手工觸發事件的解決方案,只是要針對DOM2標準和IE寫不同的程序,另外這個程序,對“原始”的註冊方式也一樣有效。請看代碼示例:

 <script type="text/javascript">
 //IE fire event
 if (form.fireEvent) {
  form.fireEvent(’onsubmit’);
  form.submit();
 //DOM2 fire event
 } else if (document.createEvent) {
  var ev = document.createEvent(’HTMLEvents’);
  ev.initEvent(’submit’, false, true);
  form.dispatchEvent(ev);
 }
</script>

    四、代碼總結

    這裏不再對各細節方法做說明,不熟悉的朋友請自行查閱相關資料。我們把整個代碼串起來:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=GBK">
 <title>submit</title>
 <script type="text/javascript" src="http://k.kbcdn.com/js/yui/build/utilities/utilities.js"></script>
</head>
<body>
 <form id="form1" action="http://www.webjx.com"></form>
 <script type="text/javascript">
  var form = document.getElementById(’form1’);
  //YUI register event
  YAHOO.util.Event.on(’form1’, ’submit’, function() {
   alert(’yui’);
  });
  //DOM0 register event
  form.onsubmit = function() {
   alert(1);
  };
  //DOM2 register event
  if (form.addEventListener) {
   form.addEventListener(’submit’, function() {
    alert(2);
   }, false);
  //IE register event
  } else if (form.attachEvent) {
   form.attachEvent(’onsubmit’, function() {
    alert(2);
   });
  }

  //IE fire event
  if (form.fireEvent) {
   form.fireEvent(’onsubmit’);
   form.submit();
  //DOM2 fire event
  } else if (document.createEvent) {
   var ev = document.createEvent(’HTMLEvents’);
   ev.initEvent(’submit’, false, true);
   form.dispatchEvent(ev);
  }
 </script>
</body>
</html>

    整個跑下來有個小問題,FX下,不需要form.submit(),直接把表單給提交出去了,所以這句也省掉了,原因知道的請回復。

    這個demo在IE6/IE7/FX下測試通過。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章