SoFunction
Updated on 2025-02-28

JavaScript DOM Add Events

Because for browsers that support DOM, adding events is to use the addEventListener() method to add events to the object!
For MSIE, attachEvent() is used to add events to the object! This makes it necessary to use a container to load the handling of events on these two different browsers! In this way, we can directly call the addEvent() method to add events to the object!
Isn't this more convenient? ! hehe……
Let's take a look!
/**
* Register a listening event to an element
* @param {Object} node The object to add event
* @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() { // This is the method for IE
node['e'+type+listener] = listener;
node[type+listener] = function(){node['e'+type+listener]( );}
( 'on'+type, node[type+listener] );
return true;
}else if () {
// This is a method for DOM-enabled browsers
( type, listener, false );
return true;
}
// If neither method is available, return false;
return false;
};
window['liujingning']['addEvent'] = addEvent;

How to use:
For example, if we want to add an event to the onload() of the page, we can write it like this:
(window,'load',function(Event) { // Write the code you want to write here}
We can also add events to an ID
var getId = ('aa');
(getId,'load',function(Event) { // Write the code you want to write here}