【问题标题】:add row to table from onload jquery从onload jquery向表添加行
【发布时间】:2023-12-02 08:58:01
【问题描述】:

我有下表

<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

这只会添加一行,它只是更改最后一行,但不会添加超过新行。

任何人都可以更正第二个脚本,因为它非常适合我的项目,因为许多其他脚本都与此相关联。

【问题讨论】:

    标签: jquery add dynamic rows


    【解决方案1】:
    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 方法的好处是您可以清理一些数据但保留其他数据。这可能对您有用。

    【讨论】:

    • +1 我认为本地克隆是要走的路。始终以处于初始状态的行的副本开始。如果需要,可以复制值。 ...我只想指出行的 ID 被复制了,但这是原始代码的一个附带问题。
    最近更新 更多