使用Jquery创建表

时间:2017-10-23 14:04:09

标签: javascript jquery datatables

我在加载DataTable时遇到错误。我没有看到任何错误。我的表是对的,我在创建表后加载了DataTable()。请注意,当我更改Dropbox并重新加载表时,我没有收到任何错误

错误在于:$('#dataTable').dataTable();

问题是什么?我需要修复它,因为这会导致Datable脚本无法工作。

  

未捕获的TypeError:无法读取属性' mData'未定义的       在HTMLTableCellElement。 (jquery.dataTables.js:1197)       在Function.each(jquery-1.9.1.js:648)       在init.each(jquery-1.9.1.js:270)       在HTMLTableElement。 (jquery.dataTables.js:1194)       在Function.each(jquery-1.9.1.js:648)       在init.each(jquery-1.9.1.js:270)       在init.DataTable [as dataTable](jquery.dataTables.js:869)       在HTMLDocument。 (accounts.js:172)       在火上(jquery-1.9.1.js:1037)       at Object.fireWith [as resolveWith](jquery-1.9.1.js:1148)



$(document).ready(function() {

    var types = [];
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());

    function DisplayTable() {
        var data;
        //Table
        $('.dataTableBody').empty();
        for(var i=1;i<=amountOfDayEnds;i++) {
            data += '<tr align="center">';
            data += '<td>' + i + '</td>';
            $.each(types, function (index, value) {
                data += '<td>' + '<input class="text-center amountOfAccounts" type="number" value="0" name="amountOfAccounts-' + value + '"  data-error="Please, insert a value"  required>' + '</td>'
            });
            data += '</tr>';
        }
        $('.dataTableBody').append(data);
    }


//Repeat the value for all rows in Clients Table
    $('.repeatForAll').change(function () {
        var number = $('.repeatForAll').val();
        $('.amountOfClients').val(number);
    });

 


    //create the interdepent selectors
    function initSelectors(){
        // next 2 statements should generate error message, see console
        MAIN.createRelatedSelector();
        MAIN.createRelatedSelector(document.querySelector('#cls') );

        //countries
        MAIN.createRelatedSelector
        ( document.querySelector('#cls')           // from select element
            ,document.querySelector('#group')      // to select element
            ,{                                               // values object
                Deposit: ['DDA','SAV'],
                Loan: ['MTG'],
            }
            ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
        );
    }

//create MAIN namespace
    (function(ns){ // don't pollute the global namespace

        function create(from, to, obj, srt){
            if (!from) {
                throw CreationError('create: parameter selector [from] missing');
            }
            if (!to) {
                throw CreationError('create: parameter related selector [to] missing');
            }
            if (!obj) {
                throw CreationError('create: related filter definition object [obj] missing');
            }

            //retrieve all options from obj and add it
            obj.all = (function(o){
                var a = [];
                for (var l in o) {
                    a = /array/i.test (o[l].constructor) ? a.concat(o[l]) : a;
                }
                return a.sort(srt);
            }(obj));
            // initialize and populate to-selector with all
            populator.call( from
                ,null
                ,to
                ,obj
                ,srt
            );

            // assign handler
            from.onchange = populator;

            function initStatics(fn,obj){
                for (var l in obj) {
                    if (obj.hasOwnProperty(l)){
                        fn[l] = obj[l];
                    }
                }
                fn.initialized = true;
            }

            function populator(e, relatedto, obj, srt){
                // set pseudo statics
                var self = populator;
                if (!self.initialized) {
                    initStatics(self,{optselects:obj,optselectsall:obj.all,relatedTo:relatedto,sorter:srt || false});
                }

                if (!self.relatedTo){
                    throw 'not related to a selector';
                }
                // populate to-selector from filter/all
                var optsfilter = this.selectedIndex < 1
                    ? self.optselectsall
                    : self.optselects[this.options[this.selectedIndex].firstChild.nodeValue]
                    ,cselect = self.relatedTo
                    ,opts = cselect.options;
                if (self.sorter) optsfilter.sort(self.sorter);
                opts.length = 0;
                for (var i=0;i<optsfilter.length;i+=1){
                    opts[i] = new Option(optsfilter[i],optsfilter[i]);
                }
            }
        }

        // custom Error
        function CreationError(mssg){
            return {name:'CreationError',message:mssg};
        }

        // return the create method with some error handling
        window[ns] = {
            createRelatedSelector: function(from,to,obj,srt) {
                try {
                    if (arguments.length<1) {
                        throw CreationError('no parameters');
                    }
                    create.call(null,from,to,obj,srt);
                }
                catch(e) { console.log('createRelatedSelector ->',e.name,'\n'
                    + e.message +
                    '\ncheck parameters'); }
            }
        };
    }('MAIN'));

    //initialize
    initSelectors();

    //get account types based on group
    $('#group').change(TypesChanged);
    $('#cls').change(TypesChanged);

    function TypesChanged() {
        selectedGroup = $('#group').val();
        switch (selectedGroup) {
            case "DDA":
                types = ["400","4044","4045"];
                break;
            case "SAV":
                types = ["300","310"];
                break;
            case "MTG":
                types = ["700","710"];
                break;
        }
        console.log("Selected group: " + selectedGroup + ", Types: " + types);
        $('.dataTableHead').empty();
        $('.dataTableFooter').empty();
        $('.dataTableHead').append('<th class="text-center">Day</th>');
        $('.dataTableFooter').append('<th class="text-center">Day</th>');
        var columnNames = [];
        $.each(types, function (index, value) {
            columnNames += '<th class="text-center">Type ' + value + '</th>';
        });
        $('.dataTableHead').append(columnNames);
        $('.dataTableFooter').append(columnNames);
        DisplayTable();
    }

    TypesChanged();
    $('#dataTable').dataTable();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>


                <div class="row text-right">
                        <label>
                            Show
                            <select name="cls" id="cls">
                                <option value="All">All</option>
                                <option value="Deposit">Deposit</option>
                                <option value="Loan">Loan</option>
                            </select>
                        </label>
                    </div>
                    <div class="row">
                        <label>
                            Show
                            <select name="group" id="group">
                                <%--Jquery--%>
                            </select>
                        </label>
                    </div>
                </div>

                    <div class="table-responsive">
                        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                            <thead class="dataTableHead">
                            <tr>
                              
                            </tr>
                            </thead>
                            <tfoot class="dataTableFooter">
                            <tr>
                                
                            </tr>
                            </tfoot>
                            <tbody class="dataTableBody">
                            
                            </tbody>
                        </table>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

首先:$('#amountOfDayEnds')指的是无处,页面上缺少元素,因此根本没有生成正文,没有行,没有任何东西可以填充。

发现问题,在.empty调用

之后,表格在页眉和页脚中缺少表格行

在下一个选择器中的函数TypesChanged()中添加tr: 从:

$('.dataTableHead').empty(); $('.dataTableFooter').empty(); $('.dataTableHead').append('<th class="text-center">Day</th>'); $('.dataTableFooter').append('<th class="text-center">Day</th>');

$('.dataTableHead').append(columnNames); $('.dataTableFooter').append(columnNames);

为:

$('.dataTableHead tr').empty(); $('.dataTableFooter tr').empty(); $('.dataTableHead tr').append('<th class="text-center">Day</th>'); $('.dataTableFooter tr').append('<th class="text-center">Day</th>');

$('.dataTableHead tr').append(columnNames); $('.dataTableFooter tr').append(columnNames);