function reference instead of function body - in a loop (with argument)
javascript
Solution
Since (as far as I know) the click handler can't take arguments, you need to make a function with the variable in scope, which should look something like this:
for( ... ) {
elementArray[i].click( onElementClick(i) );
...
}
function onElementClick( id ){
return function() {
console.log("element clicked - selectedElementIndex = " + id );
}
}
Problem
I would like to replace this: ``` for( var i=0; i<elementArray.length; i++ ) elementArray[i].click(function(){ console.log("element clicked - selectedElementIndex = " + i); }); ``` with something like: ``` for( var i=0; i<elementArray.length; i++ ) elementArray[i].click( onElementClick(i) ); function onElementClick( i ){ console.log("element clicked - selectedElementIndex = " + i ); } ``` how can I do it ? :)