使用javascript觸發(fā)事件
javascript中的事件時通過事件監(jiān)聽的機制來實現(xiàn),但是在某些情況下需要使用javascript手動觸發(fā)事件。<input type="button" id="btn1" name="" value="test" onclick="alert('click');" />
<input type="button" id="" name="" value="fire" onclick="fire();" />
如果fire按鈕來觸發(fā)test按鈕的onclick事件,fire方法可以這么寫的:<input type="button" id="" name="" value="fire" onclick="fire();" />
function fire(){
var evt = window.event?window.event:fire.caller.arguments[0];//獲取event對象
var o= document.getElementById("btn1");
if(o.fireEvent){//IE
o.fireEvent("onclick",evt);//IE下可以直接使用fireEvent方法觸發(fā)事件
}else{//other browsers
//創(chuàng)建一個對象
var event = document.createEvent("MouseEvents");
//設(shè)置event對象屬性
event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
//觸發(fā)事件
o.dispatchEvent(event);
}
}
var evt = window.event?window.event:fire.caller.arguments[0];//獲取event對象
var o= document.getElementById("btn1");
if(o.fireEvent){//IE
o.fireEvent("onclick",evt);//IE下可以直接使用fireEvent方法觸發(fā)事件
}else{//other browsers
//創(chuàng)建一個對象
var event = document.createEvent("MouseEvents");
//設(shè)置event對象屬性
event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0,
false, false, false, false, 0, null);
//觸發(fā)事件
o.dispatchEvent(event);
}
}
最開始看到這些代碼是在Wrox.Professional.JavaScript.For.Web.Developers.2nd書中,我迅速想到j(luò)query中是否有類似的實現(xiàn)?事實上我連dispatchEvent都沒有找到

事實上我想復(fù)雜了,要觸發(fā)onclick事件,直接用oBtn.click()方法即可,沒有瀏覽器兼容問題。jquery中就是直接用這個方法的。
$(function(){
$("#jqFire").click(function(){
$("#btn1").click();//works
o.click();//also works
});
});
$("#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 這個帖子介紹了幾種事件觸發(fā)的方法
http://jehiah.cz/a/firing-javascript-events-properly 一個觸發(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 衡鋒 閱讀(1092) 評論(0) 編輯 收藏 所屬分類: Web開發(fā)