2011-01-30 52 views
0

我有如下表添加行從表中的onload jQuery的

<table id="invoice"> 
    <tr> 
     <th>Quantity</th> 
     <th>Item</th> 
     <th><input type="button" id="addnew" name="addnew" value="Add Row" /> 
     </th> 
    </tr> 
    <tr id="id1"> 
     <td><input id="quantity1" name="quantity[]" tabindex="1" type="text" value="" /></td> 
     <td><select id="rate1" name="rate[]" tabindex="2" value=""> 
      <option value="">SELECT</option> 
      <option value="1">ONE</option> 
      <option value="2">TWO</option> 
     </select></td> 
     <td><input id="remove1" name="remove[]" tabindex="3" type="button" value="Remove Row"class="remove"/></td> 
    </tr> 
    </table> 

我可以使用下面的腳本

var next = 2; 
function addrow(table,add) 
{ 
    $(add).bind('click', function() { 
    var $last = $(table + ' tr:last'); 
    var last_row = $last.clone(); 
    $(last_row).find(":input").each(function() { 
     var store = $(this).attr("id"); 
     var new1 = store.replace(/1/, next); 
     $(this).attr("id",new1); 
    }); 
    last_row.appendTo($(table)) 
    $(table+" tr:last").hide().fadeIn('slow'); 
    next++; 
    }); 
} 
addrow('#invoice','#addnew'); 

Demo

添加行上面的腳本克隆第二行並追加到實際需要的表中。但問題是,如果用戶在文本框的第二行輸入一些值,然後單擊addrow,它將在新行中將值複製到值。爲了克服這一點,我只是將腳本改成了字母。

所以我改劇本以下

var next = 2; 
function addrow(table,add) 
{ 
    var $last = $(table + ' tr:last');///changed this line 
    var last_row = $last.clone(); /// changed this line 
    $(add).bind('click', function() { 

    $(last_row).find(":input").each(function() { 
     var store = $(this).attr("id"); 
     var new1 = store.replace(/1/, next); 
     $(this).attr("id",new1); 
    }); 
    last_row.appendTo($(table)) 
    $(table+" tr:last").hide().fadeIn('slow'); 
    next++; 
    }); 
} 

Demo

這增加了只有一行,它只是改變了最後一排,但不能添加比新行​​了。

任何人都可以糾正這第二個腳本,因爲這對我的項目來說是完美的,因爲許多其他腳本都與此相關聯。

回答

2
var next = 2; 

function addrow(table, add) { 
    var $last = $(table + ' tr:last'); ///changed this line 
    var last_row = $last.clone(); /// changed this line 
    $(add).bind('click', function() { 
     var localClone = last_row.clone(); // you want to clone the DOM row. 
     $(localClone).find(":input").each(function() { 
      var store = $(this).attr("id"); 
      var new1 = store.replace(/1/, next); 
      $(this).attr("id", new1); 
     }); 
     localClone.appendTo($(table)); 
     $(table + " tr:last").hide().fadeIn('slow'); 
     next++; 
    }); 
} 

您希望每次單擊它時都創建一個新的克隆/ DOM行。否則,你只是繼續移動一行。

所以我們有我們最初的最後一行克隆在開始,我們不斷克隆「乾淨的行」。乾淨的行保持乾淨,因爲last_row永遠不會被添加到DOM。

@patrickdw提到了另一個選項,它保持在click函數內部克隆最後一行,但清除該行的數據。取決於你的行是什麼樣的清理它每次都可能是值得的。

@patrickdw方法的好處是您可以清理一些數據但保留其他數據。這可能對你有用。

+0

+1我認爲本地克隆是要走的路。總是以其初始狀態中的行的重複開始。如果需要,可以複製值。 ...我只是指出該行的ID是重複的,但這是來自原始代碼的一個側面問題。 – user113716 2011-01-30 15:42:40