在选择器中使用变量from.closest()

Using variable from .closest() into a selector

本文关键字:from closest 变量 选择器      更新时间:2023-09-26

我相信这很容易做到,但我被卡住了。

我在一个页面上有多个表单,每个表单都有一个"重复"按钮。

该按钮复制一行,并将其放在每个表单内的表的末尾。表的类是".table add"。因此,我试图告诉该按钮找到最接近的表单元素,并将它添加到选择器上的路径中,但它不起作用。我知道如果我在每张表格中都填写一个身份证并要求他们,这是可行的,但这不是我想要的。谢谢你的帮助。

这是我的代码:

i=0;
$(".duplicate").on("click", function(e) {
    i++;
    $newID = 'clon'+i;
    selectedObj = $($( e.target ).closest("form"));
    alert(selectedObj.html()); //**THIS WORKS**
    $cloned = '<tr class="'+$newID+'">'+$(selectedObj+' .table-add tr:first').next().html()+'</tr>';
    $(selectedObj+' .table-add > tbody:last').append($cloned);
});

只需使用此:

var i=0;
$(".duplicate").on("click", function(e) {
    i++;
    var $newID = 'clon'+i;
    var selectedObj = $(e.target).closest("form");
    alert(selectedObj.html()); //**THIS WORKS**
    var $cloned = '<tr class="'+$newID+'">'+selectedObj.find('.table-add tr:first').next().html()+'</tr>';
    selectedObj.find('.table-add > tbody:last').append($cloned);
});

selectedObj是一个jQuery对象,因此可以使用.find()函数来选择.table-add tr:first'.table-add > tbody:last'