javascript - Runtime function declaration on event handler with variables is executing the handlers function -


i have function adds rows table , @ end there expander. when page first rendered, there 30 rows , expanders triggered mouse clicks onclick(); events described inline in document markup.

when add new onclick(); doing in loop load next 30 objects via json through xhr.

newcell.onclick = (function(id){togglecertificate(id, this, i);})(currcert['id']); 

now currcert contains integer 'id' want in handler each i, there different integer in place of currcert['id'] togglecertificate(integer id ...); expects

newcell.onclick = function(){togglecertificate(12983, this, 5);}; 

this needs passed down if refers newcell object , other 2 variables need become passed down integers interpreted when togglecertificate executed values

what doing wrong? find syntax quite tricky surrounding attaching functions event handlers.

currently code behaves trying execute "togglecertificate" data cannot debug. firebug's dom inspecter reveals attached onclick becomes

(function (){togglecertificate(currcert['id']), this, i}) 

and page begins executing correct onclick functions without being clicked , simultaneously.

i want onclick event equal string

"togglecertificate(" + currcert['id'] + ", this, " + + ");" 

sorry if words have used not proper javascript standards concerning "event handlers", "object" , "inline" -_-

you need immediate function return function:

newcell.onclick = (function(id, i) {    return function() {      togglecertificate(id, this, i);    } })(currcert['id'], i); 

onclick requires function can executed later (when there click) , output of immediate function must be. reason using immediate function @ because function attached onclick being generated programatically based on values of , currcert['id']


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -