Sometimes it is necessary to imitate some of the user's actions (mouse and keyboard operations), the most common is the mouse click. List 1, dispatchEvent ()
This is a standard method for triggering events. You must create an event object before using it. As follows:
The Code is as follows:
Var evt = document. createEvent ('event ');
Evt. initEvent ('click', true, true );
Element. dispatchEvent (evt );
2, fireEvent ()
This is the trigger event method implemented in earlier versions of IE. It does not need to create event objects and is directly used. As follows:
The Code is as follows:
Element. fireEvent ('onclick ');
Note: Like attachEvent, it needs to add "on"
A compatibility version of all browsers, as shown below
The Code is as follows:
Var dispatch = window. addEventListener?
Function (el, type ){
Try {
Var evt = document. createEvent ('event ');
Evt. initEvent (type, true, true );
El. dispatchEvent (evt );
} Catch (e) {alert (e )};
}:
Function (el, type ){
Try {
El. fireEvent ('on' + type );
} Catch (e) {alert (e )}
};
The above encapsulates a common method for triggering events, that is, various events can be triggered. The browser also provides specific methods to trigger separate events.
4, click ()
It is used to simulate user clicks. Except Safari/Chrome does not support non-input/button operations, it is supported by other browsers.
5, form. submit ()
Simulate form submission, relative to clicking input [type = submit]
6, input/textarea. select ()
Simulate the selected text.
7. focus ()
Obtains the cursor focus in a simulated manner.
8, blur ()
Simulate losing the cursor focus
9, input/textarea/select. change ()
Simulate text or option change
10. The distribution of custom events is actually to obtain the function and then call
Related:
Https://developer.mozilla.org/En/DOM/Element.dispatchEvent
Http://msdn.microsoft.com/en-us/library/ms536423%28v=VS.85%29.aspx
Https://developer.mozilla.org/en/DOM/Input.select