在jquery中向dataTable添加行的函数给出了TypeError



在我的Jquery dataTable中,row.add不起作用,并抛出一个错误,指出add函数未定义。错误消息是:

Uncaught TypeError: Cannot read property 'add' of undefined

JSFIDDLE 链接

.html

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
            </tr>
        </tfoot>
    </table>
<button id="addRow">Add new row</button>

JavaScript

$(document).ready(function() {
    var counter = 1;
    var prntTable = $('#example').dataTable( {  
       "aoColumns" : [ 
           {"bSearchable" : false}, 
           {"bSearchable" : true}, 
           {"bSearchable" : true}
        ],                                          
        "sPaginationType" : "full_numbers"
    } );
    $('#addRow').on( 'click', function () {
        prntTable.row.add( [
            counter +'.1',
            counter +'.2',
            counter +'.3'
        ] ).draw();
        counter++;
    } ); 
    $('#addRow').click();
} );

而不是:

var prntTable = $("#example").dataTable();

尝试:

var prntTable = $("#example").DataTable();

看起来旧的数据表 API dataTable()不支持您正在调用的函数。将新 API 与以下各项配合使用:DataTable() .有关详细信息,请阅读此处:数据表 API

 $('#addRow').on( 'click', function () {
       prntTable.row.add( [
            counter +'.1',
            counter +'.2',
            counter +'.3'
        ] ).draw();
        counter++;
    } ); 

在此代码中,prntTable未定义。将其定义为全局变量或在单击函数中重新定义它

添加

var prntTable = $('#example').DataTable();   

点击功能后

小提琴

尝试使用 fnAddData 它对我有用

table.fnAddData(['1','1','2','3','4']);

最新更新