我是FE,也是Fe

          前端來(lái)源于不斷的點(diǎn)滴積累。我一直在努力。

          統(tǒng)計(jì)

          留言簿(15)

          閱讀排行榜

          評(píng)論排行榜

          使用javascript觸發(fā)事件

          javascript中的事件時(shí)通過(guò)事件監(jiān)聽(tīng)的機(jī)制來(lái)實(shí)現(xiàn),但是在某些情況下需要使用javascript手動(dòng)觸發(fā)事件。
          <input type="button" id="btn1" name="" value="test" onclick="alert('click');" />
          <input type="button" id="" name="" value="fire" onclick="fire();" />
          如果fire按鈕來(lái)觸發(fā)test按鈕的onclick事件,fire方法可以這么寫的:
                  function fire(){
                      
          var evt = window.event?window.event:fire.caller.arguments[0];//獲取event對(duì)象
                      var o= document.getElementById("btn1");
                      
          if(o.fireEvent){//IE
                          o.fireEvent("onclick",evt);//IE下可以直接使用fireEvent方法觸發(fā)事件
                      }else{//other browsers
                          //創(chuàng)建一個(gè)對(duì)象
                          var event = document.createEvent("MouseEvents");
                                      
                          
          //設(shè)置event對(duì)象屬性
                          event.initMouseEvent("click"truetrue, document.defaultView, 00000
                                               
          falsefalsefalsefalse0null);
                                      
                          
          //觸發(fā)事件
                          o.dispatchEvent(event); 
                      }
                  }

          最開(kāi)始看到這些代碼是在Wrox.Professional.JavaScript.For.Web.Developers.2nd書中,我迅速想到j(luò)query中是否有類似的實(shí)現(xiàn)?事實(shí)上我連dispatchEvent都沒(méi)有找到




          事實(shí)上我想復(fù)雜了,要觸發(fā)onclick事件,直接用oBtn.click()方法即可,沒(méi)有瀏覽器兼容問(wèn)題。jquery中就是直接用這個(gè)方法的。
          $(function(){
                      $(
          "#jqFire").click(function(){
                          $(
          "#btn1").click();//works
                          o.click();//also works
                      });
                  });

          關(guān)于上面提到的createEvent/initMouseEvent/dispatchEvent/fireEvent方法可以參考下列資料:

          http://stackoverflow.com/questions/911586/javascript-simulate-mouse-over-in-code

          http://stackoverflow.com/questions/460644/trigger-an-event-with-prototype 這個(gè)帖子介紹了幾種事件觸發(fā)的方法

          http://jehiah.cz/a/firing-javascript-events-properly 一個(gè)觸發(fā)事件方法封轉(zhuǎn)

          http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6163 jquery.simulate.js的源代碼



          posted on 2010-11-29 00:17 衡鋒 閱讀(1099) 評(píng)論(0)  編輯  收藏 所屬分類: Web開(kāi)發(fā)

          主站蜘蛛池模板: 墨玉县| 滦平县| 柞水县| 汕尾市| 大足县| 赞皇县| 喀什市| 灌阳县| 库车县| 鄂托克旗| 临沂市| 开阳县| 西充县| 贵定县| 宜宾县| 华容县| 同心县| 昌黎县| 门源| 平泉县| 江口县| 红安县| 新巴尔虎左旗| 双牌县| 分宜县| 清流县| 迁西县| 通城县| 新民市| 金昌市| 四会市| 涿州市| 陆河县| 托克托县| 铜梁县| 临夏市| 紫金县| 罗甸县| 教育| 天长市| 嫩江县|