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
Post a Comment