2013-06-02 45 views
1

我有一個表格,當用戶在表格的最後一行輸入輸入時,我想附加新行。如何不止一次向表添加新行?

$('table.form-table').on('input', function() { 
    var tableID = '#' + $(this).closest('table').attr('id'); 
    if(jQuery(this).closest('tr').is(':last-child')) { 
     var currTR = $(this).closest('tr'); 
     var currTRhtml = '<tr>' + currTR.html() + '</tr>'; 
     var nextRow = jQuery(currTRhtml); 

     var checkBox = jQuery('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>'); 
     jQuery(tableID).append(nextRow); 
     checkBox.appendTo(currTR); 
    } 
}); 

和HTML代碼,如果需要(簡體/修剪):

<table class="form-table" id="XXX" border="1" cellspacing="0" cellpadding="3"> 
<thead> 
    <tr class="main"><th nowrap colspan="3" align="left" 
     class="border-left border-top border-right"> 
     <h3>XXX</h3></th> 
    </tr> 
    <tr> 
     <th>header</th> 
     </tr> 
</thead> 
<tbody> 
      <tr> 
    <input type="hidden" name="isnew" value=""> 
    <td > 
      <input type="text" 
      name="new_text" 
      value=""> 
      </td> 
      </tr> 
</tbody> 
</table> 

的問題是,這隻有一次,不會繼續追加新行。這就好像last-child過濾不會被重置... 有什麼想法?

+0

「input」是一個實際事件嗎? –

+0

@KevinBowersox - 是的,在較新的瀏覽器中,它是 – adeneo

+0

是的.html()丟失... –

回答

1

的問題是,你需要使用事件的目標,而不是「本」。現在「this」引用當前表,但需要引用當前輸入框,然後使用nearest()來查找其父tr(和first-child以確保它是最後一個)。所以,你的代碼需要看起來更像是這樣的:

$('table.form-table').on('input', function(e) { 
    var tableID = '#' + $(this).closest('table').attr('id'); 
    if ($(e.target).closest('tr').is(':last-child')) { 
     var currTR = $(e.target).closest('tr'); 
     var currTRhtml = '<tr>' + currTR.html() + '</tr>'; 
     var nextRow = $(currTRhtml); 

     var checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>'); 
     $(tableID).append(nextRow); 
     checkBox.appendTo(currTR); 
    } 
}); 

通知我傳遞的事件爲「E」,然後用$(e.target)引用當前的輸入框。

Here是一個有效的JS小提琴。

1

我懷疑問題是您需要委託input事件,因爲$(document).ready()上不存在附加的行。嘗試做這樣的事情委託處理程序:

$(document).ready(function() { 
    $('table.form-table tbody').on('input', 'tr', function() { 
     var self = $(this), 
      tableID = '#' + self.closest('table').attr('id'), 
      currTR = self.closest('tr'), 
      currTRhtml = '<tr>' + currTR.html() + '</tr>', 
      nextRow = $(currTRhtml), 
      checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>'); 
     if (currTR.is(':last-child')) { 
      $(tableID).append(nextRow); 
      checkBox.appendTo(currTR); 
     } 
    }); 
}); 

小提琴:http://jsfiddle.net/KW7ET/