jQuery click event firing immediately

前端 未结 2 744
误落风尘
误落风尘 2021-01-26 07:19

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         


        
2条回答
  •  遥遥无期
    2021-01-26 08:22

    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.

提交回复
热议问题