Introduction to event binding _ JavaScript in javascript

Source: Internet
Author: User
There are already a lot of related information about binding JavaScript events to the Internet. Today, this article is recorded by colleagues only when asked. It is a small trick in binding JavaScript events, if you can make good use of your work, there will be unexpected results. In fact, there is no new knowledge point, just to make it easy for other friends who need it to read it, it is also an accumulation for yourself, so it can only be a bit of JavaScript, and the old birds can enjoy it.
Before entering the topic, please ask a question to warm up.
The following HTML structure is available:

The Code is as follows:










And the following JavaScript code:

The Code is as follows:


Var wrap = document. getElementById ('wrapp '),
Inputs = wrap. getElementsByTagName ('input ');

For (var I = 0, l = inputs. length; I <l; I ++ ){
Inputs [I]. onclick = function (){
Alert (I );
}
}


What is the result of this execution?
/*************************** Split line***************************/
If your answer is "when you click the button, the index value of the current alert button I", then you are in my trap. You may try it. No matter which button you click, it will be alert (5 ).

Why is this seemingly natural result different from the actual situation? In fact, it is also very understandable.
Because onclick is only an event binding, rather than an execution. When we execute the onclick event, the I is already the value after the loop. As shown in this figure, each button is alert (5) that's not surprising.

So, how can we achieve "index I of the current alert button when we click? Here we need to use the concept of "closure" in JavaScript that hides xuanjicang ". We can use the closure method to rewrite the above JS and save the I value in the for loop in the memory, The Code is as follows:

The Code is as follows:


Var wrap = document. getElementById ('wrapp '),
Inputs = wrap. getElementsByTagName ('input ');

For (var I = 0, l = inputs. length; I <l; I ++ ){
(Function (cur ){
Inputs [cur]. onclick = function (){
Alert (cur );
}
}) (I)
}


Try again?It is true that alert can produce the corresponding index value, but so far it is only an appealer. The question is just beginning!
In the above method, we bind events to the button through loops and closures. We know that in JavaScript, functions are also objects, and objects occupy the memory, in the current example, there are only five buttons, and you may think that the performance overhead is negligible. However, if we have 50 or even 500 buttons, IE is already crying, when there are more other performance risks, all browsers are crying.

Back to the previous example, we can use the "event Delegate" Method to Solve the performance problem that may be caused by the increase of the binding event with the button. The principle is very simple. With Javascript event bubbling, We can bind events from buttons to their parent elements. No matter how many buttons there are, they only have one common parent element, in this way, we only need to bind an event once.
The Code is as follows:

The Code is as follows:


Var wrap = document. getElementById ('wrapp '),
Inputs = wrap. getElementsByTagName ('input ');

Wrap. onclick = function (ev ){
Var ev = ev | window. event,
Target = ev.tar get | ev. srcElement;
For (var I = 0, l = inputs. length; I <l; I ++ ){
If (inputs [I] === target ){
Alert (I)
}
}
}


Now, after the dinner is complete, we can go deep into some dessert after dinner.
In addition to performance, event delegation is more advantageous than closure event binding. Event delegation does not need to take into account the number of child elements (that is, the elements of the events to be bound. For example, after binding an onclick event, Add a button:

The Code is as follows:


Var newInput = document. createElement ('input ');
NewInput. setAttribute ('type', 'click ');
NewInput. setAttribute ('value', 'button 6 ');
Wrap. appendChild (newInput );


After adding the closure method and event Delegate method of the code, we can see that clicking "button 6" in the event binding of the closure implementation has no effect, however, if you click "button 6" for event binding implemented in the event Delegate, alert is displayed. Conversely, if we want to delete a button, the closure will still save The onclick event of the deleted button in the memory (unless it is set to null manually ), event delegation does not impose extra burden on memory. For this reason, we should also use event delegation to bind multiple elements at the same level.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.