How to set Id attribute of TDs while adding row in DataTable using row.add(data).draw().node();

为君一笑 提交于 2019-12-12 04:43:52

问题


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);
}


来源:https://stackoverflow.com/questions/33552585/how-to-set-id-attribute-of-tds-while-adding-row-in-datatable-using-row-adddata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!