Home  >  Article  >  Web Front-end  >  Detailed explanation of how to use JavaScript event binding

Detailed explanation of how to use JavaScript event binding

高洛峰
高洛峰Original
2016-11-01 12:57:59985browse

Since HTML is loaded from top to bottom, usually if we introduce a javascript file in the head section, we will add the window.onload event at the beginning of the javascript to prevent errors in DOM operations when the document is loaded. If there are multiple javascript files, it is very likely that multiple window.onload events will occur, but only one will work in the end. At this time, event binding needs to be used to solve this problem.

IE method
attachEvent(event name, function), bind event processing function
detachEvent(event name, function), unbind

DOM method
addEventListener(event name, function, capture)
removeEventListener(event name, Function, capture)

The running result of this js code is pop-up b, because there are two click events of oBtn, but only the last one is executed. At this time, the importance of event binding is reflected.

When you use event binding, both click events will be executed, but the order of execution is different in different browsers. In IE, it is executed from the bottom up, while in other browsers, it is executed from the top down. However, due to the particularity of alert, we can see the difference. Other statements are basically equivalent to no difference, but for some people who have strict time requirements, You still need to pay attention when using events. For example, in a previous article, the subtle difference in time between setInterval in the picture carousel eventually led to scrolling chaos. Image carousel domo based on native javascript

Finally organize our code into functions to facilitate subsequent use

function myAddEvent(obj, ev, fn)
{
  if(obj.attachEvent)
  {
    obj.attachEvent('on'+ev, fn);
  }
  else
  {
    obj.addEventListener(ev, fn, false);
  }
}

If you need to use multiple window.onload events at this time, it is actually almost the same as using multiple oBtn.onclick events. Just call the function as follows.

myAddEvent(window,'load',function ()
{
  alert('a');
});
myAddEvent(window,'load',function ()
{
  alert('b');


Statement:
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