The value of i
changes with each iteration of the loop. You need a closure to capture the value of i
:
(function(i) {
my_element.onclick = function () {my_function (i)};
}(i))
More Related Contents:
- JavaScript closure inside loops – simple practical example
- Event handlers inside a Javascript loop – need a closure?
- Please explain the use of JavaScript closures in loops [duplicate]
- Access outside variable in loop from Javascript closure [duplicate]
- Doesn’t JavaScript support closures with local variables? [duplicate]
- JavaScript variable binding and loop
- How does a function in a loop (which returns another function) work? [duplicate]
- Javascript closure not working
- Closures in a for loop
- passing index from for loop to ajax callback function (JavaScript)
- Javascript closures – variable scope question
- Closure in Javascript [duplicate]
- How are local variables referenced in closures? [duplicate]
- JavaScript Variable Scope [duplicate]
- javascript closure immediate evaluation [duplicate]
- Loop through an array in JavaScript
- How do I add a delay in a JavaScript loop?
- What’s the fastest way to loop through an array in JavaScript?
- Iterate through object properties
- adding ‘click’ event listeners in loop [duplicate]
- About closure, LexicalEnvironment and GC
- Is there any other way to implement a “listening” function without an infinite while loop?
- How to early break reduce() method?
- Angular filter a object by its properties
- Is optimizing JavaScript for loops really necessary?
- Javascript while loop return value
- Sum two arrays in single iteration
- closure inside a for loop – callback with loop variable as parameter [duplicate]
- Is using labels in JavaScript bad practice?
- How to access array in circular manner in JavaScript