簡體   English   中英

如何正確設置jQuery動態事件處理程序?

[英]How to set up jQuery dynamic event handlers properly?

我還是一個初學者,我嘗試使用以下代碼在動態html表的<td>中的type(text)輸入上設置動態事件處理程序:

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);
    });
}

這沒用。 i的值(如console.log中所示)不是應該的值,即連續0到4,但始終為5。但是在其他地方,我使用類似下面的示例中的模式,並且可以正常工作。

$.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);
    });
});

請,有人可以幫助您在這里找到問題嗎? 這讓我瘋狂。

其形成閉合。 因此,只需將點擊處理程序封裝在一個自執行函數中即可,該函數會創建一個新的作用域。

問題是:由於JavaScript中的變量具有函數級作用域,因此您的循環每次都會覆蓋'i'。 因此,我們可以通過創建一個新作用域的匿名函數來避免這種情況。

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)
}

舉個例子:

問題: https : //jsfiddle.net/sandenay/ar5f5m4t/

解決方案: https : //jsfiddle.net/sandenay/m5p8740w/

這也可以無循環運行

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

我有另一種棘手的方法:

$(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);
}

之后,您可以將building-html函數( .html() )與事件函數( 'keyup' )分開。

工作jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM