简体   繁体   中英

How to set up jQuery dynamic event handlers properly?

I am still a beginner, and I tried to set up dynamic event handlers on input of type(text) in <td> in a dynamic html table, with the following code:

for(var i=0; i<5; i++){
    table += '<td><input type="text" name="vote['+i+']"></td>';
    $("#table").on("keyup", "input[type='text'][name='vote["+i+"]']", function() {
        console.log("called: "+i);
        calculate(i);
    });
}

It did not work. The value of i(as displayed in console.log) is NOT what it is supposed to be, that is, 0 to 4 successively, but always 5. But elsewhere I use similar patterns like in the example below, and it works.

$.each(array_parties, function(i, objParty) {
    var stationID = objStation.stationID;
    var partyID = objParty.partyID;
    table += '<td><input type="text" name="items['+stationID+']['+partyID+']"></td>';
    $("#table").on("keyup", "input[type='text'][name='items["+stationID+"]["+partyID+"]']", function() {
        calculateTotalByParty(json, partyID, khumID);
    });
});

Please, can somebody help identify the problem here? It's driving me crazy.

Its forming a closure. So, just enclose your click handler inside a self executing function which creates a new scope.

The problem is: since a variable in JavaScript has function level scope, your loop will overwrite the 'i' each time. Hence we can avoid this by having an anonymous function which creates a new scope.

for(var i=0; i<5; i++){
(function(j){
   table += '<td><input type="text" name="vote['+j+']"></td>';
   $("#table").on("keyup", "input[type='text'][name='vote["+j+"]']", function(){
         console.log("called: "+j);
         calculate(j);
    });
})(i)
}

As an example:

Problem: https://jsfiddle.net/sandenay/ar5f5m4t/

Solution: https://jsfiddle.net/sandenay/m5p8740w/

This will work fine without loop also

$("#table").on("keyup", "input[type='text'][name^='vote']", function() {
        console.log("called: "+i);
        calculate(i);
    });

I have a different tricky approach:

$(function(){

   //First, just build the table AND SAVE THE iterator in an tag atribute
   var table = "<tr>";
   for(var i=0; i<5; i++){
      table += '<td><input type="text" name="vote['+i+']" data-id="'+i+'">   </td>';
   }
   table += "</tr>";
   $("#table").html(table);

   // On event 'keyup', get the iterator saved in attrbute ( data-id ) and use it :)
   $("#table").on("keyup", "input[type='text']", function() {
     var i = $(this).attr("data-id");
     calculate(i);
   });

});

function calculate(i){
    console.log("Called to: "+i);
}

Following this, you can separate the building-html function( .html() ) from the event function ( 'keyup' ).

Working jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM