How can I clone a table row using jQuery?

。_饼干妹妹 提交于 2021-02-11 17:55:38

问题


I want to clone my tr class row. So when the user is clicking at a button, the row will clone and will set below the last row.

I currently use the following code, only it will not work properly. I probably not be correct.

JS:

var row = jQuery('.ui-sortable').closest('.ui-sortable').find('tbody tr.row.ui-sortable:last-child');
var clone = row.clone();

The cloned field looks like this:

HTML markup:

echo '<tbody class="ui-sortable">';
echo '<tr class="row">';
echo '<td class="order">1</td>';

// Do some stuff inside the row.

echo '<td class="remove"><a class="repeatable-remove button" href="#">-</a></td>';
echo '</tr>'; // End .row
echo '</tbody>';

I think that the first snippet of code at the javascript is not correctly.


回答1:


If the button is inside the row you want to clone, then something like the following should work. (It may not be exactly right, but it's probably close).

$('#your-table').on('click', '.copy-row-button', function() {
  var 
    $table = $(this).closest('table'),
    $row = $(this).closest('tr'),
    $newRow = $row.clone();

  $table.append($('<tbody/').append($newRow));
});

I appended the row wrapped in a new <tbody> element because Internet Explorer may have problems appending a <tr> to an existing table body.

The code also uses made-up selectors for the table and the button; you can make your page with whatever id/class values you need.



来源:https://stackoverflow.com/questions/14416674/how-can-i-clone-a-table-row-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!