For browsers that support DOM, The addEventListener () method is used to add events to objects!
For MSIE, attachEvent () is used to add events to the object! This makes it necessary to use a container to load the event handling methods on these two different browsers! In this way, we can directly call the addEvent () method to add events to the object!
Isn't it more convenient ?! Haha ......
Let's take a look!
/**
* Register a listening event to an element
* @ Param {Object} the Object of the event to be added to node
* @ Param {Object} type event type
* @ Param {Object} listener event Method
*/
Function addEvent (node, type, listener ){
// Use the previous method to check compatibility to ensure smooth degradation
If (! (Node = $ (node) return false;
If (node. attachEvent) {// This is the method for IE
Node ['E' + type + listener] = listener;
Node [type + listener] = function () {node ['E' + type + listener] (window. event );}
Node. attachEvent ('on' + type, node [type + listener]);
Return true;
} Else if (node. addEventListener ){
// This method is applicable to browsers that support DOM.
Node. addEventListener (type, listener, false );
Return true;
}
// If neither method is available, false is returned;
Return false;
};
Window ['liujingning'] ['addevent'] = addEvent;
Usage:
For example, if we want to add an event to the onload () of the page, we can write as follows:
Liujingning. addEvent (window, 'load', function (Event) {// write the code you want to write here}
We can also add events to an ID.
Var getId = document. getElementById ('A ');
Liujingning. addEvent (getId, 'load', function (Event) {// write the code you want to write here}