【问题标题】:Why does my HTML table lose bootstrap datatable attributes when it is refreshed with ajax?为什么我的 HTML 表在使用 ajax 刷新时会丢失引导数据表属性?
【发布时间】:2019-08-13 23:45:14
【问题描述】:

我有一个 HTML 表格存储在 table.html:

<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
</table>

另一个页面包含一个名为“newtable”的 div,一个 ajax 脚本用于获取 table.html 的内容,将其插入名为“newtable”的 div 中并每 5 秒刷新一次。 该表使用引导数据表,这为我的表添加了一个搜索框和分页功能:

<body>
<div class="content table-responsive table-full-width newtable">

</div>
</body>

    <script>
        function table() {
            $.ajax({
                url: 'table.html',
                type: 'get',
                success: function(response){
                    $('.newtable').html(response);
                }
            });
        }

                table();
        setInterval(table, 5000);

$(document).ready(function() {
    $('#example').DataTable();
} );


    </script>
</html>

当页面加载时,我的表格工作正常,但是在 ajax 刷新表格内容后,表格更新但是引导数据表功能(搜索栏和分页)消失,除非我自己刷新页面,否则不会重新出现.

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery html ajax datatables


    【解决方案1】:

    当您调用$('#example').DataTable() 时,它会修改表格的内容以添加所有功能。但是,由于您的 ajax 调用正在更改表格的内部 HTML ($('.newtable').html(response)),所有这些内容都会丢失。加载新数据后可以再次调用DataTable()

    success: function(response){
        $('.newtable').html(response);
        $('.newtable').DataTable();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2020-04-14
      • 1970-01-01
      • 2011-11-22
      相关资源
      最近更新 更多