在没有克隆值

时间:2017-06-27 13:58:42

标签: javascript jquery html tr

我有简单的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); 


            });

        });

2 个答案:

答案 0 :(得分:0)

假设您要保留克隆的所有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('');

答案 1 :(得分:0)

尝试使用以下代码:

    $(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); 
        });

    });