添加" id"属性为数据表行

时间:2014-03-29 19:04:54

标签: 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' );

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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' );

答案 2 :(得分:0)

我们可以在使用fnRowCallback

呈现表格后添加行的属性
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
          if(aData[0] == "A"){
                $(nRow).attr( 'data-blah',"modal" );
                $(nRow).attr( 'style',"display:none" );
          }
    }

有关fnRowCallback

的详细信息

工作demo

相关问题