2011-01-30 56 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