首页 > 解决方案 > 在 Javascript 中重用函数调用 [数据将重复孪生]

问题描述

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

代码

HTML

    <ul class="nav nav-pills mytab">
       <li class="nav-item">
          <a class="nav-link active" bankid="1" href="#test1" data-toggle="tab"><i class="fa fa-university"></i> test1</a>
      </li>
                                                                                                                    <li class="nav-item">
         <a class="nav-link" bankid="2" href="#test2" data-toggle="tab"><i class="fa fa-university"></i> test2</a>
    </li>
    </ul>

<table id="table_{{$bvl['id']}}" class="table table-bordered table-striped" cellpadding="0px" width="auto" cellspacing="0px">
                                        <thead id="headD">
                                            <tr></tr>
                                            <tr></tr>
                                        </thead>
                                        <tbody id="dataD" runat="server"></tbody>
                                        <tfoot>
                                            <tr></tr>
                                        </tfoot>
                                    </table>

Javascript

 $('.mytab a').on('click', function (e) {
                var bankid = $(this).attr("bankid");
                getTableMeta(bankid);
            })

//get column data
function getTableMeta(bankid) {
    table          = "";
    ColumnData     = "";
    EditRowData    = [];
    mdataArray     = [];
    isEditAllState = false;
    defaultcol     = "";

    $('#table_'+bankid+' thead tr:first-child th').remove();
    $('#table_'+bankid+' thead tr:nth-child(2) th').remove();
    $('#table_'+bankid+' thead tr:first-child td').remove();
    $('#table_'+bankid+' thead tr:nth-child(2) td').remove();

    $.ajax({
        type: 'POST',
        url: "{{route('getcolumn')}}",
        data: {
            "_token": "{{ csrf_token() }}",
        },
        dataType: 'json',
        success: function (data) {

            ColumnData   = data.Column;
            var inputype = "";
            $.each(data.Column, function (index, element) {
                //title
                $('#table_'+bankid+' thead tr:first-child').append($('<th>', {
                    text: element.Name
                }));

                //insert
                if (data.Insertable == true) {
                    if (element.Editable == true) {
          
                        if(element.Name == 'in' || element.Name == 'out'){
                            inputype = 'number';
                        }else if(element.Name == 'time'){
                            inputype = 'time';
                        }else{
                            inputype = 'text';
                        }

                        $('#table_'+bankid+' thead tr:nth-child(2)').append($('<th class="'+element.Name+'"><input class="'+element.Name+'Add_'+bankid+'" style="width: 99% " type="'+inputype+'" /></th>'));
                    }else{
                        $('#table_'+bankid+' thead tr:nth-child(2)').append($('<th></th>'));
                    }
                }

                mdataArray.push({ mData: element.Name, class: element.Name });
            });

            if (data.Deletable == true) {
                $('#table_'+bankid+' thead tr:first-child').append($('<th>', {
                    text: 'Action'
                }));
                mdataArray.push({ defaultContent: '<span class="deleteBtn"><i class="fa fa-trash-o fa-lg" aria-hidden="true"></i></span>', class: 'DeleteRow' });

            }
            if (data.Insertable == true) {
                $('#table_'+bankid+' thead tr:nth-child(2)').append($('<td><span class="insertBtn"><i class="fa fa-plus fa-lg" aria-hidden="true"></i></span></td>'
                ));
            }
            defaultcol = data.Column[0].Name;
            //once table headers and table data property set, initialize DT
            initializeDataTable(bankid);

        }
    });
}

//get row data
function initializeDataTable(bankid) {

    table = $('#table_'+bankid).DataTable({
        "ajax": {
            url: "{{route('getcolumndata')}}",
            "type": "POST",
             data: function (data) { 

                editIndexTable = -1;
                var colname;
                var sort = data.order[0].column;
                if (!data['columns'][sort]['data'] == '')
                    colname = data['columns'][sort]['data'] + ' ' + data.order[0].dir;
                //in case no sorted col is there, sort by first col
                else colname = defaultcol + " asc";
                var colarr = [];
                var colfilter, col;
                var arr = {
                    'draw': data.draw, 
                    'length': data.length,
                    'sort': colname, 
                    'start': data.start, 
                    'search': data.search.value,
                    'bankid': bankid,
                    '_token': "{{ csrf_token() }}"
                };
                //add each column as formdata key/value for filtering
                data['columns'].forEach(function (items, index) {
                    col = data['columns'][index]['data'];
                    colfilter = data['columns'][index]['search']['value'];
                    arr[col] = colfilter;
                });
                
                return arr;
            }
           
        },
        "bSortCellsTop": true,
        "orderable": false,
        "destroy": true,
        "lengthMenu": [10, 50, 100],
        "iDisplayLength": 100,
        "searching": true,
        serverSide: true, 
        "processing": true,
        "columnDefs": [{ 'targets': 1, 'visible': false }],
        aoColumns: mdataArray
    });

    //for insert button
    $("#table_"+bankid+" thead").on('click', 'tr td span.insertBtn', function (e) {
        console.log("a"); //here will console duplicate data depend on the tab user click
        insertRowData(this.parentNode.parentNode, bankid);
    });

}

问题: 我使用引导导航选项卡创建了一个选项卡。对于每个选项卡,它将具有bankID,具体取决于用户单击,并将传递bankID并呈现数据表。上面的代码工作正常,但它会面临一个重复调用的问题。这是否意味着,如果用户随机播放并点击选项卡 1(test1)选项卡 2(test2),当他们尝试插入数据时会出现重复输入问题。我试图console.log里面的onClick函数,它会有多个控制台。这取决于用户单击选项卡的次数。例如,当他们第一次单击选项卡 2(test2)然后单击选项卡 1(test1)然后再次单击选项卡 2(test2),它将有 2 个重复输入。任何人都可以在这方面提供帮助吗?我被这个问题困扰了很长时间:(

标签: javascripthtmljquerydatatable

解决方案


你能在你的点击功能之前使用这个代码吗?

$('.mytab a').off('click');

对于添加行单击

$("#table_"+bankid+" thead tr td span.insertBtn").off('click');

$("#table_"+bankid+" thead").on('click', 'tr td span.insertBtn', function (e) {
    console.log("a"); //here will console duplicate data depend on the tab user click
    insertRowData(this.parentNode.parentNode, bankid);
});

推荐阅读