【问题标题】:cloning tr of a table without cloning the values克隆表的 tr 而不克隆值
【发布时间】:2017-06-27 13:58:42
【问题描述】:

我有一个简单的 jquery 外部 java 脚本,它克隆表的最后一行并将行中字段的 id 增加 1。如果在克隆值之前行中有数据,我现在在克隆时遇到问题也复制了。我正在尝试克隆时克隆行中输入字段的值属性为空。

jquery javascript 代码:

 $(document).ready(function () {
            $("#btn_AddTruck").click(function () {
               var $tableBody = $('#tbl_invTruck').find("tbody"),
                $trLast = $tableBody.find("tr:last"),
                $trNew = $trLast.clone();
                // Find by attribute 'id'
                $trNew.find('[id]').each(function () {
                    var num = this.id.replace(/\D/g, '');
                    if (!num) {
                        num = 0;
                    }
                    // Remove numbers by first regexp
                    this.id = this.id.replace(/\d/g, '') 
                        // increment number
                        + (1 + parseInt(num, 10));
                });

                $trLast.after($trNew); 


            });

        });

【问题讨论】:

  • Java 和这个无关......
  • 您可以构建一个没有值的隐藏 tr,仅用于克隆。

标签: javascript jquery html tr


【解决方案1】:

假设您要保留克隆的所有td 子元素,但只清除它们的内容:

$trNew.find('td').html('');

$(document).ready(function () {
  $("#btn_AddTruck").click(function () {
    let $tableBody = $('#tbl_invTruck').find("tbody");
    let $trLast = $tableBody.find("tr:last");
    let $trNew = $trLast.clone();
    
    $trNew.find('td').html('')
    
    $trLast.after($trNew); 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="btn_AddTruck">Click me<button>

<table id="tbl_invTruck">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

如果你不关心任何子元素,你可以清除tr元素的innerHTML:

$trNew.html('');

【讨论】:

  • 我也尝试过这种方法,它正在克隆表格行但根本没有任何数据。我真的很想克隆该行并将输入字段的 value 属性留空
【解决方案2】:

尝试使用以下代码:

    $(document).ready(function () {
        $("#btn_AddTruck").click(function () {
           var $tableBody = $('#tbl_invTruck').find("tbody"),
            $trLast = $tableBody.find("tr:last"),
            $trNew = $trLast.clone();
            // Find by attribute 'id'
            $trNew.find('[id]').each(function () {
                var num = this.id.replace(/\D/g, '');
                if (!num) {
                    num = 0;
                }
                // Remove numbers by first regexp
                this.id = this.id.replace(/\d/g, '') 
                    // increment number
                    + (1 + parseInt(num, 10));
            });
            //empty the td content
            $trNew.find("td").html(""); 
            $trLast.after($trNew); 
        });

    });

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2013-08-07
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    相关资源
    最近更新 更多