0

I am sure this is something very easy to do, but I'm stuck.

I have multiple forms in a page each one with a "duplicate" button.

The button duplicates a row and put it at the end of a table that is inside of each form. The class of the tables is '.table-add'. So I'm trying to tell the button to find the closest form element and add it to the path on my selector, but it is not working. I know it can work if I put an ID in each form and call for them, but that's not what I want. Thanks for help.

This is my code:

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);
});
4

1 回答 1

3

只需使用这个:

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'.

于 2013-06-27T19:21:39.413 回答