javascript - How to pass a specific array element for a callback of event -


i have array of objects holds each "actionbutton" id, selector , callback

var actionbuttons = [     {         id:"0",         selector:"._55ln._qhr",         callback: undefined     },     {         id:"1",         selector:"._22aq._jhr",         callback: undefined     },     .     .     . ]; 

what i'm trying calling function specific parameter array(the id) every time selector clicked.

for(var i=0;i<actionbuttons.length;i++){     $(document).on('click', actionbuttons[i].selector, function() {         makeaction(actionbuttons[i].id);         if (actionbuttons[i].callback)             actionbuttons[i].callback(this);     }); } 

but code not working; looks every time callback function called value of i equal array size.

how can solve problem;ie. make value of variable i become different each callback.

the issue because i variable being incremented in loop. means when first event handler runs after loop completes, i maximum value, not 0.

to fix can use closure:

for(var = 0; < actionbuttons.length; i++) {   (function(i) {     $(document).on('click', actionbuttons[i].selector, function() {       makeaction(actionbuttons[i].id);       if (actionbuttons[i].callback)         actionbuttons[i].callback(this);     });   })(i); } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -