Home > Web Front-end > JS Tutorial > JavaScript DOM adding events_javascript tips

JavaScript DOM adding events_javascript tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:56:01
Original
1077 people have browsed it

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}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template