to pass argument to event handler

F

fusillo

My code pass a value of a variable to the event handler's argument by
means of eval statement

here's:

//statements setting evt
for (var i=0; i<evt.periodi.length; i++){
//evt.periodi is an array of objs
a=document.createElement("a");
a.onclick=eval('function (){ cancellaCal(' + evt.periodi.id_evt_cal
+ '); };');
a.appendChild(document.createTextNode("cancella"));
//another statements
}

Without eval trick evt.periodi.id_evt_cal is undefined within handler
function.
Is there a better solution?




Thanks
fusillo
 
L

Lasse Reichstein Nielsen

fusillo said:
My code pass a value of a variable to the event handler's argument by
means of eval statement

here's:

for (var i=0; i<evt.periodi.length; i++){ ....
a.onclick=eval('function (){ cancellaCal(' + evt.periodi.id_evt_cal
+ '); };'); ....
Is there a better solution?


Since you need each function value to have different values for "i",
you need a different variable for each. The simplest way to achieve
that is to create a new scope using a function expression and call
it immediately:

a.onclick = (function(local){
return function(){ cancellaCal(local); };
})(evt.periodi.id_evt_cal);

/L
 
F

fusillo

Lasse Reichstein Nielsen ha scritto:
a.onclick = (function(local){
return function(){ cancellaCal(local); };
})(evt.periodi.id_evt_cal);

/L


your solution is very cool.
thanks for your help.

fusillo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top