Functional link instead of function body - in a loop (with argument)

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 this?:)

+4
source share
4 answers

Since (as far as I know) the click handler cannot accept arguments, you need to make a function with a variable in the scope, which should look something like this:

 for( ... ) { elementArray[i].click( onElementClick(i) ); ... } function onElementClick( id ){ return function() { console.log("element clicked - selectedElementIndex = " + id ); } } 
+4
source

Replace:

 elementArray[i].click( onElementClick(i) ); 

WITH

 elementArray[i].click( onElementClick(elementArray[i].id)); 
+1
source

Wrap it in a function expression:

 elementArray[i].click(function() { onElementClick(i); }); 

You also need to wrap the code in a function expression to avoid sticky issues:

 (function() { ... for ( ... ) (function(i) { elementArray[i].click(function() { onElementClick(i); }); })(i); })(); 
0
source

Using data , it might look like this:

 for (... { elementArray[i].click( onElementClick ).data('id',i); } function onElementClick(){ console.log("element clicked - selectedElementIndex = " + $(this).data('id') ); } 
0
source

Source: https://habr.com/ru/post/1447623/


All Articles