jQuery中有很好用的trigger来触发事件,但总不能写什么都去引入jQuery吧
一个简单的需求,实现类似IE下的fireEvent效果<要兼容其它主流浏览器>
关于这二个方法,没记得起来,然后就google了一把:
IE下:
createEventObject Method
语法:
oNewEvent = object.createEventObject( [oExistingEvent])
创建的事件对象,也可以取消冒泡、阻止默认事件。(cancelBubble、returnValue)
例子:
<html> <body> <script> function OuterClick() { if(event.expando == "from_inner") { alert("Event actually fired by clicking on inner DIV!") } else { alert("Event fired by clicking on outer DIV!") } } function InnerClick() { var eventObj = document.createEventObject(); // Set an expando property on the event object. This will be used by the // event handler to determine what element was clicked on. eventObj.expando = "from_inner"; parent.document.all.Outer.fireEvent("onclick",eventObj); event.cancelBubble = true; } </script> <div id="Outer" onclick="OuterClick()" style="height:200;200;padding:50;background-color:mistyrose"> <div id="Inner" onclick="InnerClick()" style="height:100;100;padding:25;background-color:lavender"></div> </div> </body> </html>
msdn地址:http://msdn.microsoft.com/en-us/library/ms536390(VS.85).aspx
FF遵循并实现了W3C对DOM 2、DOM 3的事件定义:
语法:
var event = document.createEvent(type);
例子:
function simulateClick() { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var cb = document.getElementById("checkbox"); var canceled = !cb.dispatchEvent(evt); if(canceled) { // A handler called preventDefault alert("canceled"); } else { // None of the handlers called preventDefault alert("not canceled"); } }
选创建事件对象,然后派发此事件对象,派发的返回值可以检测事件处理句柄是否阻止也默认事件(返回false则被阻止)
访问MDC关于createEvent的说明:https://developer.mozilla.org/en/DOM/document.createEvent
回到最初的起点,如果只是想实现类似fireEvent的方法:
var elem = xxx;
if (document.createEventObject && elem.fireEvent) { elem.fireEvent('onclick'); } else if (document.createEvent){ var evt = document.createEvent('MouseEvents'); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent(evt); }