jQuery复制表格行

50
我有一个带有“添加”按钮的表格。当您单击此按钮时,我希望在当前行下面创建一行新的表格行。我还希望这一行中的输入字段为空。我正在尝试使用 .clone() 实现此目的,但它会克隆页面上的所有行。请帮忙解决。谢谢。
$("input.tr_clone_add")
        .live('click', function(){
              $(this).closest('.tr_clone')
                    .clone()
                    .insertAfter(".tr_clone")
         });

HTML

=>

HTML

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<tr>
<td>Name</td>
<td>Location</td>
<td>From</td>
<td>To</td>
<td>Add</td>
</tr>
<tr class="tr_clone">
<td><input type="text" autofocus placeholder="who" name="who" ></td>
<td><input type="text" autofocus placeholder="location" name="location" ></td>
<td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
</tr>
</table><!-- /table#table-data -->

我猜你也想更新name参数以避免数据冲突(即新行中输入的值覆盖克隆行的值)...? - Tomm
嗨Tomm,我没有想到名称值会发生冲突,我本来想在某个时候添加一个区分器,也许可以在tr类中添加一个数字? - Clinton Green
2
我通常使用一个“模板”进行克隆,该模板通过CSS样式设置为“display: none”。 - hafichuk
1
几件事情:(1)widthbordercellpaddingcellspacing属性已被弃用,应改用CSS样式。请转换为CSS。(2)对于表头单元格,请使用TH而不是TD元素。(3)您不能拥有多个自动聚焦字段。 - Šime Vidas
@Šime Vidas,感谢您注意到这一点。干杯 - Clinton Green
7个回答

81

你的问题在于你的 insertAfter

.insertAfter(".tr_clone")

在每个.tr_clone后插入:

匹配的元素集将被插入到由此参数指定的元素之后。

你可能只想在复制的行上使用after。并且使用一些.find(':text').val('')来清除克隆文本输入框中的内容;像这样:

var $tr    = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);

演示: http://jsfiddle.net/ambiguous/LAECx/ 或者对于现代 jQuery:http://jsfiddle.net/ambiguous/LAECx/3274/

我不确定哪个输入框应该获得焦点,所以我没有改变它。


2
@mzvarik 为什么呢?在一个 $ 符号前面加上是为了提醒你这里用的是jQuery封装过的元素而不只是普通的元素。如果因为习惯打PHP代码而到处都加 $,那就是一个坏习惯。但在这种情况下又有所不同。 - mu is too short
.live() 已经被弃用,请不要使用。 - Sensoray
@Sensoray 的 live 只出现在2011年的原始示例中。 - mu is too short
1
我意识到了,我只是在评论中写下来,以便其他查看它的人知道。我试图找出不同的方法,并尝试实时操作,但并没有知道/检查答案发布的日期,因为它被标记为正确。也许你可以编辑/添加注释,以便其他查看它的人也能知道:] - Sensoray

19

这里是你需要的:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

演示: http://jsfiddle.net/RhjxK/4/


更新: jQuery中委托事件的新方式是

$(table).on('click', '.tr_clone_add', function () { … });

.closest('tr) 后面加上 [0] 的原因是什么?在 fiddle 中,为什么要写成 table = $( '#table-data' )[0]?为什么不直接写成 var thisRow = $(this).closest('tr');?(顺便说一句,这个例子很有帮助,点赞 +1) - cssyphus
@gibberish 在 jQuery 对象上应用 [0] 将返回该 jQuery 对象内的第一个 DOM 元素。这种模式是我旧习惯 - 我喜欢直接将对 DOM 对象的引用存储在变量中。在这种情况下,您可以将其省略,因为我们将 thisRow 变量传递给新的 $(),它不关心是否接收包含 DOM 对象的 jQuery 对象或 DOM 对象。 - Šime Vidas
非常有帮助,感谢Sime。我总是关注你的回答,它们写得很好、聪明且富教育意义。此外,恭喜你 webPlatformDaily 取得越来越大的成功。看到你深刻的文章被最优秀的人所赞赏,十分值得;干得漂亮。 - cssyphus

12

以下代码将复制最后一行并在表格中添加到最后一行之后:

var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();

$trLast.after($trNew);

工作示例:http://jsfiddle.net/kQpfE/2/


太好了!适合我。 - Taffarel Xavier

4
尝试这个变体:
$(".tr_clone_add").live('click', CloneRow);

function CloneRow()
{
    $(this).closest('.tr_clone').clone().insertAfter(".tr_clone:last");
}

2

请试试这个。

HTML

<!-- Your table -->
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data"> 
    <thead>
        <tr>
            <th>Name</th>
            <th>Location</th>
            <th>From</th>
            <th>To</th>
            <th>Add</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" autofocus placeholder="who" name="who" ></td>
            <td><input type="text" autofocus placeholder="location" name="location" ></td>
            <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
            <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
            <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
        </tr>
    <tbody>
</table>

<!-- Model of new row -->
<table id="new-row-model" style="display: none"> 
    <tbody>
        <tr>
            <td><input type="text" autofocus placeholder="who" name="who" ></td>
            <td><input type="text" autofocus placeholder="location" name="location" ></td>
            <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
            <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
            <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
        </tr>
    <tbody>
</table>

脚本

$("input.tr_clone_add").live('click', function(){
    var new_row = $("#new-row-model tbody").clone();
    $("#table-data tbody").append(new_row.html());
});

0
非常简单,只需按下按钮就可以使用jquery克隆最后一行:
您的表HTML:
<table id="tableExample">
    <thead>
        <tr>
            <th>ID</th>
            <th>Header 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Line 1</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2"><button type="button" id="addRowButton">Add row</button></td>
        </tr>
    </tfoot>
</table>

JS:

$(document).on('click', '#addRowButton', function() {
    var table = $('#tableExample'),
        lastRow = table.find('tbody tr:last'),
        rowClone = lastRow.clone();

    table.find('tbody').append(rowClone);
});

敬礼!


0

尝试这段代码, 我使用了以下代码来克隆和删除克隆的元素,我还使用了新类(newClass),可以自动添加到新克隆的HTML中。

用于克隆...

 $(".tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var newClass='newClass';
    var $clone = $tr.clone().addClass(newClass);
    $clone.find(':text').val('');
    $tr.after($clone);
});

用于删除克隆元素。

$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
});

HTML如下所示

<tr class="tr_clone">
                       <!-- <td>1</td>-->
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span10" readonly>
                        <span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接