将"id"属性添加到Datatable行

use*_*497 3 jquery-datatables

这是一个修剪过的代码片段,我向表中添加一个新行,然后尝试将id属性添加到结果"tr"中,以便稍后可以找到该行.当我尝试添加属性时,可能还没有渲染行?有没有更好的方法来实现这一目标?

test = [0,1,2,3,4,5,6,7,8,9,10];

node = $('#MyDataTable').DataTable().row.add( test );

// this doesn't seem to work - need to end up with: "<tr id='MyUniqueID'>"
node.to$().attr('id', 'MyUniqueID' );
Run Code Online (Sandbox Code Playgroud)

van*_*inv 8

您可以像这样使用"createRow"回调:

$("#your-id").DataTable({
    // Define custom handler for createdRow event
    "createdRow" : function( row, data, index ) {

        // Add identity if it specified
        if( data.hasOwnProperty("id") ) {
            row.id = "row-" + data.id;
        }       
    }
});

// Add some data
var data = ["col-1","col-2","col-3","col-4"];

// Arrays are objects in javascript, so you can add custom properties to your array and read them in createdRow callback
data.id = "your-id";

// Create row in ordinary way
$("#your-id").row.add(data)
    .draw();
Run Code Online (Sandbox Code Playgroud)


小智 5

在Jquery DataTables中,通常会添加数据fnAddData(),它会返回刚添加的行的索引(如果插入了多行,则返回多个索引).您可以使用该索引来定位行fnGetNodes()

test = [0,1,2,3,4,5,6,7,8,9,10];
var rowIndex = $('#MyDataTable').dataTable().fnAddData(test);
var row = $('#MyDataTable').dataTable().fnGetNodes(rowIndex);
$(row).attr( 'id', 'MyUniqueID' );
Run Code Online (Sandbox Code Playgroud)