About binding an event in a for loop the print variable i is the last time.

Source: Internet
Author: User

In fact, the external variable referenced by the function is the last value.

<! DOCTYPE html>        #box {            width:100px;            height:100px;            background-color:pink;        }    </style>    <script src= "index.js" ></script>///////////////////////////////JS Code////////////////////////// Window.onload = function() {    var box = document.getElementById ("box");    var num = 0; function A () {console.log (num);} Box.onclick = function() {num + +; a ();//1,2,3,4 .... Each time Click adds 1, indicating that the function refers to an external variable as the last value that references that variable. }}

Let's look at one more example:

Window.onload = function() {    var box = document.getElementById ("box");    var num = 0;    for (var i=0;i<10;i++) {        Box.onclick = function() {            console.log (i);//always print ten }  }} 

If you know the scope chain is much better, in this function I actually refers to the last time I value, why not 1,2,3,4 ...? Because in your for loop, you didn't execute the function, you did it when you clicked, and when you execute the function, it finds that it doesn't have the variable i, so I'm looking for the variable i in its scope chain, because when you click the box, the For loop is done, So the value of I stored in the scope chain is 10, and finally it prints out 10.

for (var i=0;i<10;i++) {    function A () {        console.log (i);    }    A (); 1,2,3,4,5 ....} 

Why is this possible? Because you have executed function A in the loop variable i, what the natural variable i is printed out.

Now you know why it's the last time the value of the For loop is printed when the event is bound.

If you know how to understand this, I believe you know how to solve the problem.

Workaround 1: Let the function execute directly.

Workaround 2: Save the variable i in each for loop to somewhere.

Method 1:

Window.onload = function() {    var box = document.getElementById ("box");    var num = 0;    for (var i=0;i<10;i++) {        Box.onclick = A ();        function A () {console.log (i);//1,2,3,4        ...}}}

Although this can be printed out each time the value of the variable i, but we did not click on the box when it has been executed, directly ignore the click event, that is, the click event is optional, so we use this method in the binding event is not so usable, then we use Method 2 try it.

Method 2:

Window.onload = function() {    var div = document.getelementsbytagname ("div");    var num = 0;    for (var i=0;i<div.length;i++) {        (function(i) {            Div[i].onclick = function() {Console.log ( i); }}) (i)}      }

The value of each i is printed successfully by the self-executing function, and the variable i is saved to the parameter of the self-executing function. If you do not know what a self-executing function can look at the first knowledge of the closure in JS section.

How do you think we should choose that? Certainly look at your situation, if there is no binding event, that is, let this function directly execute, then use Method 1, otherwise use Method 2, another method 2 general, but because the inside I will be saved to memory to compare the reasons for consumption performance, so in the absence of necessary circumstances, try not to use this way, You can also bind I to attributes on an element.

About binding an event in a for loop the print variable i is the last time.

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.