在jQuery中添加行到dataTable的函数会出现TypeError错误

4

在我的Jquery dataTable中,row.add不起作用,并且抛出一个错误,说添加函数未定义。错误信息如下:

Uncaught TypeError: Cannot read property 'add' of undefined

jsfiddle link

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();
} );
3个回答

18

改为:

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

尝试:

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

看起来旧的datatables API dataTable()不支持你正在调用的函数。请使用新的API:DataTable()。阅读此处以获取更多信息:Datatable API


2
这解决了我的问题。旧的dataTable()甚至不应该存在。 - Howard

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

        counter++;
    } ); 

在这段代码中,prntTable未定义。要么将其定义为全局变量,要么在click函数中重新定义它。
添加
var prntTable = $('#example').DataTable();   

点击函数之后

Fiddle


我遇到了错误:Uncaught TypeError: Cannot read property 'add' of undefined。 - Prasanth A R
这个小提琴对我来说很好用。你有检查过吗? - Outlooker
未定义错误是由上述原因引起的。在检查之前,请清除您的浏览器缓存,伙计。 :) - Outlooker
3
我认为需要注意的是 Ankur 下面的回答有助于澄清答案。尽管 Outlooker 建议使用 DataTable,但我第一次阅读时忽略了 D 的大写。如果您正在使用 dataTable,则 table.row.add() 将无法工作,您必须使用 DataTable。这解决了我遇到的问题,并且我已经在 Outlooker 的 fiddle 中验证过了。 - N1mr0d

2

尝试使用fnAddData,这对我有效。

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

2
table.fnAddData(['1','1','2','3','4']); 我遇到了错误,提示 table.fnAddData 不是一个函数。 - krishna patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接