简体   繁体   English

jQuery DataTable 添加行第一位置

[英]jQuery DataTable add row first position

var clientTable = $("#table").DataTable();
clientTable.row.add([1,1,1,1]).draw(false);

I add new row in my datatable with this code but I need to add row in first position of the table.我使用此代码在数据表中添加新行,但我需要在表的第一个位置添加行。

How can I do this ?我该怎么做?

According to the documentation "The rows that are added are subjected to the ordering and search criteria that are applied to the table, which will determine the new row's position and visibility in the table" - so, the new row's position in the table is dependent on the data.根据文档“添加的行受应用于表的排序和搜索条件的约束,这将确定新行在表中的位置和可见性” - 因此,新行在表中的位置是相关的在数据上。 If you apply a sort ordering to the table, the new row may be added first - depending on the data.如果对表应用排序顺序,则可能首先添加新行 - 取决于数据。 If you don't have a column that would fit for that, you can add a hidden column with a counter and sort by that (see the below snippet for example).如果您没有适合它的列,您可以添加一个带有计数器的隐藏列并按其排序(例如,请参见下面的代码段)。

Alternately, you can consider using the RowReorder extension或者,您可以考虑使用RowReorder扩展

 $(document).ready(function() { var t = $('#example').dataTable( { 'columns': [ {'title': 'id', 'visible': false}, {'title': 'data'} ], 'order' : [[1,'desc']] } ); var counter = 1; $('#addRow').on( 'click', function () { t.api().row.add( [ counter, 'data for id: ' + counter ] ).draw( false ); counter++; } ); // Automatically add a first row of data $('#addRow').click(); } );
 <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script> </head> <button id="addRow">Add New Row</button> <table id="example" class="display" width="100%" cellspacing="0" /> </html>

Actualy, is not possible with DataTable default function.实际上,使用 DataTable 默认函数是不可能的。

Do it with jQuery :用 jQuery 来做:

$('#tableName tr:first').after("<tr role="row"><td></td><td>Your Row</td></tr>");

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

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