简体   繁体   English

jquery:重新附加<tr>到<tbody>删除它们后

[英]jquery: reappend <tr>s to <tbody> after removing them

I have to buttons: Add , there I want to add s to my (they come from a selected number) and Reset where want to remove those elements.我必须按钮: Add ,我想将 s 添加到我的(它们来自选定的数字)和Reset想要删除这些元素的位置。 I know I need to clone DOM elements after removing them, but how do I implement it.我知道我需要在删除 DOM 元素后克隆它们,但我该如何实现它。 I´m relatively new to JS.我对 JS 比较陌生。 Alternatively I can switch to a checkbox with this solution here: with checkbox and cloning Any help appreciated - thks.或者,我可以在这里使用此解决方案切换到复选框:使用复选框和克隆感谢任何帮助-谢谢。

 <!DOCTYPE html> <html lang="en"> <head> <title>reprex jquery</title> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function() { // what´s the value of the integer input? var no = 10; let i = 1; $("#btn-add").click(function() { while (i <= no) { $("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>"); $("#tbl input")[i-1].setAttribute("name", "s" + i); $("#tbl input")[i-1].setAttribute("value", i); $("#tbl textarea")[i-1].setAttribute("name", "c" + i); ++i; } }); }); $(document).ready(function() { $("#btn-remove").click(function() { $("#tbl tr:gt(0)").remove(); }); }); </script> </head> <body> <div> <button class="btn" id="btn-add" type="button">Add</button> <button class="btn" id="btn-remove" type="button">Reset</button> </div> <table id="tbl"> <thead> <tr> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> </tbody> </table> </body> </html>

You can add back your rows by checking the status of i .您可以通过检查i的状态来添加您的行。 Since it's defined more globally, as you continue to use it, the value changes.由于它的定义更加全球化,因此随着您继续使用它,值会发生变化。 Consider the following.考虑以下。

 $(function() { var no = 10; var i = 1; $("#btn-add").click(function() { if (i > 1) { i = 1; } while (i <= no) { $("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>"); $("#tbl input")[i - 1].setAttribute("name", "s" + i); $("#tbl input")[i - 1].setAttribute("value", i); $("#tbl textarea")[i - 1].setAttribute("name", "c" + i); ++i; } }); $("#btn-remove").click(function() { $("#tbl tbody tr").remove(); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div> <button class="btn" id="btn-add" type="button">Add</button> <button class="btn" id="btn-remove" type="button">Reset</button> </div> <table id="tbl"> <thead> <tr> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> </tbody> </table>

Here you can see that i is changed in your while .在这里您可以看到i在您的while中发生了变化。 You may need to reset it when the User clicks on "Add" button.当用户单击“添加”按钮时,您可能需要重置它。

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

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