简体   繁体   English

克隆jquery后如何追加和删除元素?

[英]How to append and remove element after clone jquery?

I want to make like the following picture.我想做下图。 Displays the delete button on the previous element and places the add button for the next element.在上一个元素上显示删除按钮并为下一个元素放置添加按钮。 Example例子

I already made it, but I don't know how to add and delete at the same time.我已经做了,但是我不知道如何同时添加和删除。

 var btn_delete = '<button type="button" onclick="removeKolom($(this))">Delete</button>'; function removeKolom(e){ e.parents('.kolom').remove(); } function addElement(e) { $(".kolom:last").clone().appendTo(".data-repeater"); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table border="1"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>Act</th> </tr> </thead> <tbody class="data-repeater"> <tr class="kolom"> <td>One</td> <td>Two</td> <td>Three</td> <td class="btn-repeater"> <button class="add-btn-repeat" onclick="addElement($(this))" type="button">Add</button> </td> </tr> </tbody> </table>

 var btn_delete = '<button type="button" onclick="removeKolom($(this))">Delete</button>'; var btn_add = '<button class="add-btn-repeat" onclick="addElement($(this))" type="button">Add</button>'; function removeKolom(e) { e.parents('.kolom').remove(); } function addElement(e) { var newElement = $(".kolom").first().clone(); $(".kolom").find('button.add-btn-repeat').replaceWith(btn_delete); newElement.appendTo(".data-repeater").find('button').replaceWith(btn_add); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table border="1"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>Act</th> </tr> </thead> <tbody class="data-repeater"> <tr class="kolom"> <td>One</td> <td>Two</td> <td>Three</td> <td class="btn-repeater"> <button class="add-btn-repeat" onclick="addElement($(this))" type="button">Add</button> </td> </tr> </tbody> </table>

You can modify your addElement function as following:您可以按如下方式修改addElement函数:

function addElement(e) {
   var $kolomLast = $(".kolom:last");
   $kolomLast.clone().appendTo(".data-repeater");
   $kolomLast.find(".add-btn-repeat").replaceWith(btn_delete);
}

You can keep a reference to the last row element and once it is cloned, you can change its button from Add to Delete .您可以保留对最后一行元素的引用,一旦它被克隆,您就可以将其按钮从Add更改为Delete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM