参考:
http://www.jb51.net/article/27971.htm
https://developer.mozilla.org/en-US/docs/DOM/element.dispatchEvent
例子:
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"); } }
1. 创建事件
https://developer.mozilla.org/en-US/docs/DOM/document.createEvent
创建一个指定类型的事件。
语法:
var event = document.createEvent(type);
event
is the created Event object.type
is a string that represents the type of event to be created. Possible event types include"UIEvents"
,"MouseEvents"
,"MutationEvents"
, and"HTMLEvents"
. See Notes section for details.
2. 根据不同的事件类型调用不同的初始化事件函数:
Event Module | Event type to pass to createEvent | Method to be used to initialize the event |
---|---|---|
DOM Level 2 Events | ||
User Interface event module | "UIEvents" |
event.initUIEvent |
Mouse event module | "MouseEvents" |
event.initMouseEvent |
Mutation event module | "MutationEvents" |
event.initMutationEvent |
HTML event module | "HTMLEvents" |
event.initEvent |
3. 事件派发
bool = element.dispatchEvent(event)
element
is thetarget
of the event.event
is an event object to be dispatched.- The return value is
false
if at least one of the event handlers which handled this event called preventDefault. Otherwise it returnstrue
.
例子: https://developer.mozilla.org/samples/domref/dispatchEvent.html