数据表不适用于使用MVC动态创建的表

时间:2018-11-05 14:08:14

标签: javascript jquery asp.net-mvc datatable datatables

我在mvc应用程序中的数据表存在问题,mvc具有一种常见的布局,即母版页(布局页

我通常在适用于所有子页面的母版页(布局页)中实现了数据表

现在,我面临一个挑战,那就是某些表是在选择组合框时动态创建的

布局页面

$('.table').DataTable({
        "aoColumnDefs": [
                          {
                              bSortable: false,
                              aTargets: [-1], /* 1st one, start by the right */
                              "defaultContent": "",
                          }
        ],
        "fixedHeader": true,
        "lengthChange": false,
        "bPaginate": false,
        "responsive": true,
        "autoWidth": false,
        "scrollY": "300px",
        "scrollCollapse": true,
        "paging": false,
        initComplete: function (settings, json) {
            this.api().columns().header().each(function (th) {
                $(th).removeClass("sorting_asc");
                $(th).removeClass("sorting");
            }
         )
        },
    });

儿童(部分查看)

<div class="row">
                <div class="col-md-12">
                    <br />
                    <div id="example"></div>                        
                </div>
            </div>

function GetEmails() {
        var tbl = $('#example');
        $.ajax({
            url: '/test/GetTestData',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);                
        }).error(function (result) {
            alert("Fail");
        });
    }

现在,我有一个问题

 tbl.empty().append(result);  

在div中追加表之后,数据表不适用于该表,我想知道如何在布局页面中通知该表已追加在页面中

让我知道,javascript或jquery中有任何在添加后触发的事件或其他事件?

预先感谢

2 个答案:

答案 0 :(得分:1)

尝试一下, 它的工作

function ApplyDataTable()
{      
$('#example').bind('DOMNodeInserted', function (event) {
    if (event.type == 'DOMNodeInserted') 
    {
    //Datatable for search and sorting
    $(currntTable).DataTable({
    "aoColumnDefs": [
                      {
                          bSortable: false,
                          aTargets: [-1], /* 1st one, start by the right */
                          "defaultContent": "",
                      }
    ],
    "fixedHeader": true,
    "lengthChange": false,
    "bPaginate": false,
    "responsive": true,
    "autoWidth": false,
    "scrollY": "300px",
    "scrollCollapse": true,
    "paging": false,
    });      
    } 
});
}

答案 1 :(得分:0)

您可以在ajax成功的情况下初始化数据表,

  $('.Table').DataTable();

但是,如果您真的只想从布局中添加数据表,那么这应该会有所帮助

 $(document).ajaxComplete(function (event, xhr, settings) {
        $('.Table').DataTable();
    });