Since html is loaded from top to bottom, usually if we introduce javascript files in the head part, we will add events at the beginning of javascript to prevent errors in DOM operations when the document is loaded. If there are multiple javascript files, it is very likely that multiple events will occur, but only one of them will work in the end. At this time, event binding is needed to solve this problem.
IE method
attachEvent (event name, function), bind event handling function
detachEvent (event name, function), unbinding
DOM method
addEventListener(event name, function, capture)
removeEventListener(event name, function, capture)
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled document</title> <script> =function () { var oBtn=('btn1'); =function () { alert('a'); }; =function () { alert('b'); }; }; </script> </head> <body> <input type="button" value="Button" /> </body> </html>
The result of this code running b pops up because there are two oBtn click events, but only the last one is executed, which reflects the importance of event binding.
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled document</title> <script> =function () { var oBtn=('btn1'); //IE browser if() { ('onclick', function () { alert('a'); }); ('onclick', function () { alert('b'); }); } //Other browsers else { ('click', function () { alert('a'); }, false); ('click', function () { alert('b'); }, false); } }; </script> </head> <body> <input type="button" value="Button" /> </body> </html>
When you use event binding, the two clicks will be executed, but the execution order is different in different browsers. In IE, it is executed from the bottom up, while in other browsers, it is from the top down. However, due to the special nature of alert, we can see the difference. Other statements are basically equivalent to no difference. However, when it comes to using events with strict time requirements, it is still necessary to pay attention to it. For example, in an article, a subtle difference in time in the picture carousel of setInterval, the end result of scrolling confusion. Image carousel domo based on native javascript
Finally, our code is organized into a function for easier use later
function myAddEvent(obj, ev, fn) { if() { ('on'+ev, fn); } else { (ev, fn, false); } }
At this time, if you need to use multiple events, it is actually similar to using multiple events. Just call the function as follows.
myAddEvent(window,'load',function () { alert('a'); }); myAddEvent(window,'load',function () { alert('b');
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.