在动态添加的元素上绑定更改事件

时间:2016-01-14 10:06:55

标签: javascript jquery html javascript-events

我有这个html表:

<table id="sanityTestsTable" border="1">
<tbody>
<tr>
   <th>ID</th>
   <th>Sanity Check</th>
   <th>Result</th>
</tr>
<tr>
   <td>1</td>
   <td><input name="sanityItem" size="20" maxlength="255" type="text"></td>
   <td>Not available yet</td>
</tr>
<tr>
   <td>2</td>
   <td><input name="sanityItem" size="20" maxlength="255" type="text"></td>
   <td>Not available yet</td>
</tr>
</tbody></table>

每当用户在input字段中输入任何内容时,我都希望添加新的空input字段。这适用于jQuery:

$("input[name='sanityItem']").change(function(){
   var emptyRows = 0;
   $("#sanityTestsTable tbody > tr td:nth-child(2) input").each(function(){ 
      if ( $(this).val() == "" ) 
         emptyRows++; 
   });      
   if ( emptyRows < 2 ) {
      $("#sanityTestsTable tbody > tr").each(function(index){
         if ( $(this).is($("#sanityTestsTable tbody > tr:last")) ) {
            var txt1 = "<tr><td>" + (index + 1) +"</td><td><input name=\"sanityItem\" size=\"20\" maxlength=\"255\" type=\"text\"></td><td>Not available yet</td></tr>";  
            $(txt1).insertAfter(this);
            var lastRow = $("#sanityTestsTable tbody > tr:last");                
            // This does not work:
            lastRow.on("change", null, lastRow, $("input[name='sanityItem']").change() );
         }
      });
   }
});

如果新插入的行未捕获change事件。仅在编辑初始行1或2时添加新行。当您将文本输入新行(例如3)时,我还想要追加空行。 .on()电话的正确用法是什么?我也试过.bind(),但也没有成功。

经过多次“尝试和错误”后,我明白了:

function changeHandler() {
        var emptyRows = 0;
        $("#sanityTestsTable tbody > tr td:nth-child(2) input").each(function(){ if ( $(this).val() == "" ) emptyRows++; });        
        if ( emptyRows < 2 ) {
            $("#sanityTestsTable tbody > tr").each(function(index){
                if ( $(this).is($("#sanityTestsTable tbody > tr:last")) ) {
                    var txt1 = "<tr><td>" + (index + 1) +"</td><td><input name=\"sanityItem\" size=\"20\" maxlength=\"255\" type=\"text\"></td><td>Not available yet</td></tr>";  
                    $(txt1).insertAfter(this);
                    // Attach change handler to last row
                    $("#sanityTestsTable tbody > tr:last td:nth-child(2) input").on("change", function() { changeHandler() });
                }
            });
        }

}

$("input[name='sanityItem']").change( function() {changeHandler()} );

0 个答案:

没有答案