简体   繁体   English

使用jQuery动态更新DataTable内容

[英]Update the DataTable contents dynamically using jquery

I have a HTML table with empty tbody, which gets populated in jquery function on selecting some filters(typically select options). 我有一个带有空tbody的HTML表,在选择某些过滤器(通常是选择选项)时,将在jQuery函数中填充该表。 The DataTable is used for pagination if the table elements exceeds the limit. 如果表元素超出限制,则使用DataTable进行分页。

When the filter is applied for the first time, it works fine. 首次应用过滤器时,它可以正常工作。 But when the table contents are updated by jquery, DataTable doesn't seem to update it with new data. 但是,当表内容由jquery更新时,DataTable似乎不会使用新数据对其进行更新。

HTML looks like: HTML看起来像:

<table class="table table-striped table-hover outline" id="result" >
    <thead>
       <tr>
           <th>Name</th>
           <th>ID</th>
           <th>Age</th>        
           <th>Department</th>  
       </tr>
    </thead>
    <tbody>
    </tbody>
</table>

And the Jquery function: 和Jquery函数:

$(document).ready(function(){

    function filterData(list) {

        /*filter and send updated list*/

        return list;
    }

    /* some other code */
    data = filterData(rawData); //Function will filter the data

    var html = ''; //html part to be appended in the results table

    data.forEach(function(d) {
        html += '<tr>'; //create a table row
        for (var key in d) 
            html += '<td>'+ d[key] +'</td>';   //put all elements in the columns
        html += '</tr>';     
    });

    $("#result tbody").html(html); //display the result in table body

    $('#result').DataTable({
        scrollY:"300px",
        lengthMenu: [10,15,20]
    });

});

Any possible way to update the DataTable with new contents? 有什么可能的方法来用新内容更新DataTable? Thanks in advance! 提前致谢!

You can use standard DataTable API's to add row dynamically. 您可以使用标准的DataTable API来动态添加行。

var myDatatable = $('#result').DataTable({
        scrollY:"300px",
        lengthMenu: [10,15,20]
    });


data.forEach(function(d) {
     var html += '<tr>'; //create a table row
        for (var key in d) 
            html += '<td>'+ d[key] +'</td>';   //put all elements in the columns
        html += '</tr>';     

       // add row using standard API's and draw the table again
       myDatatable.row.add(html).draw();

    });

You need to use the following functionalities in datatable to update the table. 您需要在数据表中使用以下功能来更新表。

datatable.rows.add(newDataArray);
datatable.draw();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM