jQuery dataTables将id添加到添加的行

Seb*_*ien 11 jquery datatables

是否可以使用jQuery DataTables向最后添加的行添加ID(例如<tr id="myid">...</tr>)?

$('#example').dataTable().fnAddData( [
        "col_value_1",
        "col_value_2",
        "col_value_3",
        "col_value_4" ] );
Run Code Online (Sandbox Code Playgroud)

(将id添加到此新行)

dco*_*ith 23

使用fnCreatedRow/createdRow回调.最好在创建行时设置表行的id属性.使用API​​提供的内容,您不需要破解它或使用凌乱的代码

创建TR元素(并且已插入所有TD子元素)时调用此函数,或者在使用DOM源时注册,允许操作TR元素(添加类等).

//initialiase dataTable and set config options
var table = $('#example').dataTable({
    ....
    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'my' + iDataIndex); // or whatever you choose to set as the id
    },
    ....
});

// add data to table post-initialisation
table.fnAddData([
    'col_value_1',
    'col_value_2',
    'col_value_3',
    'col_value_4'
]);
Run Code Online (Sandbox Code Playgroud)

  • 我同意.说真的,你不能提供一行ID?这就像非常基本的功能.如果你不能通过ID定位它们,你还能如何编辑/删除现有行?当然,它们会自动获取ID,但是您想要使用自己的ID的频率是多少,因为应用程序已经构建好了? (2认同)

Rol*_*n C 8

这对我有用

var MyUniqueID = "tr123"; // this is the uniqueId.
var rowIndex = $('#MyDataTable').dataTable().fnAddData([ "column1Data", "column2Data"]);
var row = $('#MyDataTable').dataTable().fnGetNodes(rowIndex);
$(row).attr('id', MyUniqueID);
Run Code Online (Sandbox Code Playgroud)


Sam*_*mie 8

这是我在这里找到的更清洁的方法:

table.row.add( [ ... ] ).node().id = 'myId';
table.draw( false );
Run Code Online (Sandbox Code Playgroud)