I’m attempting to register an anonymous function when a user clicks a cell in an HTML table. Here’s some of the raw, unadulterated code:
document.getElementById( 'course'+displayed_year_index+occurrences_indices[displayed_year_index]).onclick = eval('function() {PrintReceipt('+result.years[result_year_index].rul_code+');};');
Note the use of eval, since this sits in a loop and the anonymous function is different each time round.
Suffice to say, this works absolutely fine in Firefox 2. But, Firefox 3 throws a ‘Syntax Error’, pointing inside the brackets after the word ‘function’.
Does anybody have any smart ideas on how I can fix this?
Just to make it crystal clear what I’m attempting to do, here’s a much simplified example:
for (index=0; index<4; index++) { document.getElementById('div'+index).onclick = eval('function () {Foo(index);};'); }
In other words, I wish to trigger the same function with a different parameter value for each div.
IMHO closures should not be used in this case and there is no need to create a new function for each onlick (uses much more memory than necessary) and eval is the wrong answer.
You know that the element you are getting with getElementById is an object and that you can assign values to it?
But you should define the PrintReceipt first: