要将新行插入表中的某个索引处,请使用jQueryval()
和insertBefore()
方法。您可以尝试运行以下代码以了解如何在表中插入新行-
<html> <head> <title>jQuery Example</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('#index').val($('#myTable tbody tr').length); $('#btn1').click(function(){ var indx = $('#index').val()-1; var newRow = $('<tr><td>New row is added at index '+$('#myTable tbody tr').length+'</td></tr>'); newRow.insertBefore($('#myTable tbody tr:nth('+indx+')')); }); }); </script> </head> <body> <table id="myTable"> <tbody> <tr> <td>This is row 1</td> </tr> <tr> <td>This is row 2</td> </tr> </tbody> </table> <input id="index"/> <button type="button" id="btn1">Add</button> </body> </html>