克隆上一个 tr 行并将其追加到当前表

Clone and append previous tr row to current table

本文关键字:追加 上一个 tr      更新时间:2023-09-26

我有一个包含 3 行的表格,其中包含可以填充值的输入。

现在我在最后一个tr中有一个链接,上面写着" + More"。

"+ 更多"链接,如果按预期工作,应克隆上述 tr 并将其附加到链接上方。

这就是我有多远:

http://jsfiddle.net/9s8LH/2/

$(document).ready(function(){
    $('.appendRow').bind('click', function(){
        var $table = $(this).closest('table');
        var $tr = $(this).closest('tr');
        var $trAbove = $(this).prev('tr');
        $table.append($tr.clone());
    });
});

试图在我里面的那个之前使用prev('tr')来抓取 TR 元素,但它并没有真正起作用。

第二个问题是它附加到 +More TR 下,而不是在其上方。

如何做到这一点?

$(this).prev('tr')不起作用的原因是您的appendRow类位于链接上,而不是行上。链接之前没有trprev查看前一个同级元素(同级元素 = 在同一父级中),以查看它是否与选择器匹配。它不会扫描,也不会向上移动层次结构。

不过你已经很接近了,见评论:更新的小提琴

$(document).ready(function(){
    $('.appendRow').bind('click', function(){
        // First get the current row
        var $tr = $(this).closest('tr');
        // Now the one above it
        var $trAbove = $tr.prev('tr');
        // Now insert the clone
        $trAbove.clone().insertBefore($tr);
    });
});

请注意使用 insertBefore ,这会在当前行之前插入克隆。

尝试使用 on() 来动态添加元素,你的 HTML 应该是这样的,

.HTML

<table class="extraBookingBox">
    <tr><td>Fees</td><td>Amount</td></tr>
    <tr>
        <td><input type="text" style="width: 40px;" name="cancelfee_price[]" />€</td>
        <td><input type="text" style="width: 40px;" name="cancelfee_price[]" />€</td>
    </tr>
    <tr>
        <td colspan="2"><a href="#" class="appendRow">+ More</a></td>
    </tr>
</table>

脚本

$(document).ready(function(){
    $(document).on('click','.appendRow', function(){        
        var $tr = $('table tr:nth-child(2)').clone(); 
        console.log($tr);
        $tr.insertBefore($('.appendRow').closest('tr'));        
    });
});

演示