在jQuery dataTables中的所选行之后添加一行

use*_*079 2 jquery datatables jquery-datatables

DataTable被定义为

var oTable = $('#table1').dataTable({
    'aaData': [
                 ['John', 'ABC', '$90000'], ['Doe', 'XYZ', '$100000'], ['Alan', 'PQR', '$110000']
              ],
    'aoColumns': [
                 {'sTitle': 'Name'}, {'sTitle': 'Company'}, {'sTitle': 'Salary'}
     ]
});
Run Code Online (Sandbox Code Playgroud)

空行添加为

oTable.fnAddData([' ', ' ', ' ']);
Run Code Online (Sandbox Code Playgroud)

但是,这会增加表格的底部。有没有一种方法可以在所选行的正下方/正上方添加。

dav*_*rad 5

认为您太急于接受自己不能做自己想做的事情:)当然可以,但是很难弄清楚在哪种情况下。这个问题不是很具体。以下代码在您单击的最后一行之后插入一个新行:

var dataTable;
var options = {
    bSort: false,
    bPaginate: false
};

function initDataTable() {
  dataTable = $('#example').dataTable(options);
}

function attachClickHandler() {
    $("#example tbody tr").click(function(event) {
        var index=$(this).index();
        $("#insert").text('insert a row below the row you just clicked ('+index+')').attr('index',index).show();
    });
}

$("#insert").click(function() {
    var index=$(this).attr('index');
    var newRow = '<tr>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>' +
        '</tr>';
    dataTable.fnDestroy();
    $("#example tbody tr").eq(index).after(newRow);    
    initDataTable();
    attachClickHandler();
});

initDataTable();
attachClickHandler();
Run Code Online (Sandbox Code Playgroud)

想法是将新行插入到基础DOM表中,然后在完成后重新初始化dataTable。它也可以通过排序工作,但是出于演示目的,我关闭了排序。正如@scottysmalls提到的那样,dataTables实际上是对所有内容进行排序,因此将立即对新插入的行进行排序,这看起来好像是未正确插入的行。

参见演示-> http://jsfiddle.net/2AqQ6/