首页 > 解决方案 > 数据表不适用于使用 MVC 动态创建的表

问题描述

我在 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 中是否有任何事件在追加或其他内容后触发?

提前致谢

标签: javascriptjqueryasp.net-mvcdatatabledatatables

解决方案


试试这个,它的工作

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,
    });      
    } 
});
}

推荐阅读