Home > Web Front-end > JS Tutorial > body text

How to use JavaScript events to execute multiple processes in series_javascript skills

WBOY
Release: 2016-05-16 19:17:16
Original
1058 people have browsed it

I recently used JavaScript event processing mechanism and found some information.
When writing JavaScript programs in the past, events were all used

Copy code The code is as follows:

Object.event = handler;

is initialized. This method is common for Internet Explorer, Mozilla/Firefox and Opera. But one problem is that this method can only correspond to one event processing process. It is not easy to use if you want an event to execute multiple processing processes in sequence.
But Internet Explorer has provided an attachEvent method since 5.0. Using this method, you can assign multiple processing processes to an event. attachEvent is also applicable to current Opera. But the problem is that Mozilla/Firefox does not support this method. But it supports another addEventListener method, which is similar to attachEvent and is also used to assign multiple processing procedures to an event. But there are some differences in the events they assign. In the attachEvent method, the event starts with "on", but in addEventListener, the event does not start with "on". In addition, addEventListener has a third parameter. Generally, this parameter is specified as false. That's it.
So if you want to assign multiple processing procedures to an event in your program, you only need to first determine the browser, and then choose to use attachEvent or addEventListener according to different browsers. The example is as follows:
Copy code The code is as follows:

if (document.all) {
window.attachEvent('onload', handler1);
window.attachEvent('onload', handler2);
}
else {
window.addEventListener('load', handler1, false) ;
window.addEventListener('load', handler2, false);
}
Note: The execution order of multiple processes assigned by attachEvent is random, so the execution order between these processes is random. Don't have order dependencies. In addition, attachEvent and addEventListener are not only applicable to window objects, but other objects also support this method.
Copy code The code is as follows:

function addEvent(obj, evenTypeName, fn){
if (obj.addEventListener){
obj.addEventListener(evenTypeName, fn, true);
return true;
} else if (obj.attachEvent){
return obj.attachEvent("on " evenTypeName, fn);
} else {
return false;
}
}
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template