How do I set the "id" attribute of one TD when I add a new row using this API of Datatables? Consider I have only one TD.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here is an example from the API that performs an operation on newly added rows.
var table = $('#example').DataTable();
table
.rows.add( [
new Pupil( 43 ),
new Pupil( 67 ),
new Pupil( 102 )
] )
.draw()
.nodes()
.to$()
.addClass( 'new' );
.addClass()
is a jquery method that they use here to add class="new"
to the newly added rows.
So, instead of adding a class to the row, you could find all <td>
in that row using .find()
, then use .each()
to call a function on each <td>
to modify its id attribute using .attr()
.
var table = $('#example').DataTable();
var count = 0;
table
.rows.add( [
new Pupil( 43 ),
new Pupil( 67 ),
new Pupil( 102 )
] )
.draw()
.nodes()
.to$()
.find('td')
.each(function() {
$(this).attr('id', 'td' + (count++) );
});
Notice the use of a count
variable to ensure that each id assigned is unique.
回答2:
instead of using the count in the solution above, you can use the index created by jQuery-
.find('td')
.each(function(**index**) {
$(this).attr('id', 'td' + **index** );
});
回答3:
Adding to let's say one of the column in td (say only 4th):
var datatableTable = $('#datatableTable').DataTable();
var json = JSON.parse(data);
for (var row in json) {
var toAdd = {
id: json[row].id,
name: json[row].name
};
var i = datatablePojectListTable.row.add(toAdd).draw().nodes().to$().find('td:eq(4)').each(function() {$(this).attr('id', 'td-' + idVal );});
// Add ID to row
datatablePojectListTable.rows(i).nodes().to$().attr("id", idVal);
}