Monday, 2 October 2017

Consider this code:

var elements = document.getElementsByTagName('input');
var n = elements.length;    // assume we have 10 elements for this example
for (var i = 0; i < n; i++) {
    elements[i].onclick = function() {
        console.log("This is element #" + i);
    };
}
In view of the above code, if there were 10 input components, clicking any of them would show "This is component #10"! This is on the grounds that, when onclick is conjured for any of the components, the above for circle will have finished and the estimation of I will as of now be 10 (for every one of them).

Here's the way we can remedy the above code issues, however, to accomplish the coveted conduct:

var elements = document.getElementsByTagName('input');
var n = elements.length;    // assume we have 10 elements for this example
var makeHandler = function(num) {  // outer function
     return function() {   // inner function
         console.log("This is element #" + num);
     };
};
for (var i = 0; i < n; i++) {
    elements[i].onclick = makeHandler(i+1);
}

In this reconsidered adaptation of the code, makeHandler is quickly executed each time we go through the circle, each time accepting the then-current estimation of i+1 and restricting it to a perused num variable. The external capacity restores the internal capacity (which additionally utilizes this checked num variable) and the component's onclick is set to that inward capacity. This guarantees each onclick gets and utilizes the best possible I esteem (through the checked num variable).



Related Posts:

0 comments:

Translate

GoogleTech786. Powered by Blogger.

Subscribe Youtube

Our Facebook Page

Wikipedia

Search results

Popular Posts

Adsense