I have the following code in the web app I\'m developing:
var bgcolor = \'\';
var row = 0;
for(var i = 0; i < result.data.length; i++)
{
// Set alternatin
You are calling the function yourself here .click( show_result_dialog(i, result) );
There is a difference between invoking a function show_result_dialog()
and passing its reference show_result_dialog
.
You need to either pass your arguments as event data:
.click( {index: i, result: result}, show_result_dialog );
or simply wrap it in an anonymous function:
.click( function() { return show_result_dialog(i, result) });
You have at least two problems that I can see.
The first, as identified by other posters, is not writing function() { ... }
around the call to show_result_dialog()
.
The second, is using .click
instead of .on
. The former method is (confusingly) used to both register and to trigger click handlers, whereas the latter can only register. If you had used .on
the problem would likely have been much easier to see.
The third is that you're trying to use a loop variable inside a closure, which never works. i
will have the last value it had at the end of the loop, not the value it had when the call to .click
was made.
The simplest fix for the latter problem is to use the data
parameter to .on()
to pass the required parameters:
$("#view_results_" + result.data[i]['record_id'] ).on('click', {
row: i, result: result
}, show_result_dialog);
function show_result_dialog(ev) {
var row = ev.data.row;
var result = ev.data.result;
...
}
Other (more efficient) methods exist to solve the loop problem, but this will work and is pretty trivial to understand.