Datatables .row() is undefined

2019-06-14 21:58发布

问题:

i want to delete rows by simply clicking related Button.. data tables is works, i can use some basic function like sort and search in datatable, but when i click the button it just simply said undefined error :

for your information, im using datatable 1.10 and jquery 1.10.2

Code :

<table cellpadding="0" cellspacing="0" border="0" class="row-border" id="table">
<thead>
    <th>Video ID</th>
    <th>Filename</th>
    <th>Action</th>
</thead>
<tbody>
    <td>1</td>
    <td>ABCD</td>
    <td><input type='button' name='deleteBtn' value='Delete' />
</tbody>
<tfoot>
    <tr>
        <th>Video ID</th>
        <th>Filename</th>
        <th>Action</th>
    </tr>
</tfoot>
</table>

<script src="jquery.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script type="text/javascript">
var table = $('#table').dataTable( {} );

$('#table tbody').on('click',"input[type='button']",function() {
    table
        .row( $(this).parents('tr') )**
        .remove()
        .draw();
});
</script>
</body>
</html>

回答1:

It does not work, because there is a huge difference between the dataTable() constructor and the DataTable() constructor introduced in 1.10.x (see docs) :

The difference between the two is that the first will return a jQuery object, while the second returns a DataTables API instance.

Simply change

var table = $('#table').dataTable( {} );

to

var table = $('#table').DataTable( {} );

if you want to work on the new dataTables API through the table variable.
See your code working -> http://jsfiddle.net/Sd6UQ/

NB : Remember to use <tr>..</tr> and close <td>'s properly. dataTables can be very sensitive to malformed markup.



回答2:

if you decide to create the datatable on this way

table = $('#table').dataTable( {} )

you will obtain a jQuery object in table var but you can access to the dataTable api with the following instruction

table.api()

you could see it running here

http://jsfiddle.net/Sd6UQ/

you could use that Technic if you have no access to the datatable creation instruction

<script>
    //datatable creation is in another file
    //$('#table').dataTable( {} )

    $("button[name'deleteBtn']").click(function(){
        var row = $(this).closest("tr");
        var table = row.closest('table').dataTable();
        table.api()
             .row( row )
             .remove()
             .draw();
    })
<script>

you could see it working here

http://jsfiddle.net/r2ue74zn/



回答3:

You can simply add the following code to reload datatable

//var table = $('#table').dataTable( {} );
table.ajax.reload();