Home >Web Front-end >JS Tutorial >JavaScript DOM adding events_javascript tips
Because for browsers that support DOM, adding events is to use the addEventListener() method to add events to objects!
For MSIE, attachEvent() is used to add events to objects! This makes it necessary for us to use a container to load the event processing methods 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? ! Haha...
Let’s take a look!
/**
* Register a listening event to the element
* @param {Object} node The object to add the 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(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 is a method for browsers that support DOM
node.addEventListener( type, listener, false );
return true;
}
// If neither method is available, return false;
return false;
};
window['liujingning']['addEvent'] = addEvent;
Usage:
For example, if we want to add an event to onload() of the page, we can write like this:
liujingning.addEvent(window,'load',function(Event) { //Write the code you want to write here}
We can also add events to a certain ID
var getId = document.getElementById('aa');
liujingning.addEvent(getId,'load',function(Event) { //Write you here code to write}