JQuery单击事件正在多次执行

时间:2017-05-31 01:51:15

标签: jquery asp.net-mvc datatables

我正在尝试使用以下代码列向数据表添加新列,这些列正在添加多次。在第一次单击添加一列,然后在第二次单击添加2列等。你能帮我解决这个问题。我使用下面的代码添加新列

function triptable(tablename, isTripIn, addColumnButton, saveButton) {
    this.tableName = tablename;
    this.istripin = isTripIn;
    this.dataTable = null;
    this.rowNum = 1;
    this.colNum = 0;
    this.rowCell = 0;
    this.colCell = 0;
    this.iterator = 0;
    this.colsList = [];
    this.tableData = [{}];
    this.oTable = null;
    this.inEditMode = null;
    this.addColumnId = addColumnButton;
    this.saveId = saveButton;
    this.init();
}

triptable.prototype = {
    init: function () {
        this.getSchedules();
    },
    getSchedules: function () {
        var req = $.ajax({
            type: "GET",
            url: "/ScheduleManagement/ScheduleManagement/GetSchedules/",
            dataType: "json",
            context: this,
        });

        req.done(function (result) {
            this.colsList = [];
            var returnedData = JSON.parse(result);
            if (returnedData.length > 0) {
                var obj = returnedData[0];
                for (var key in obj) {
                    var attrName = key;
                    var attrValue = obj[key];
                    var column = {
                        "mData": key,
                        "mDataProp": key,
                        "sTitle": key,
                        "sType": "string"
                    };
                    this.colsList.push(column);
                }
                results = returnedData;
                var stop = this.colsList[this.colsList.length - 1];
                var i = this.colsList.indexOf(stop);
                if (i != -1) {
                    this.colsList.splice(i, 1);
                }

                this.colsList.unshift(stop);
                this.colNum = this.colsList.length;
                this.tableData = returnedData;
                this.setTable();
                this.oTable = this.dataTable;
            }
        });
    },
    setTable: function () {
        //Construct the measurement table
        this.dataTable = $('#' + this.tableName).dataTable({
            "bJQueryUI": true,
            "bDeferRender": true,
            "bInfo": false,
            "bSort": false,
            "bDestroy": true,
            "bFilter": false,
            "bPagination": false,
            "aaData": this.tableData,
            "aoColumns": this.colsList,
        });
        this.unbindTableEvents();
        //this.bindTableEvents();

    },

    saveRow: function (oTable, nRow) {
        var jqInputs = $('input', nRow);
        oTable.fnUpdate(jqInputs[0].value, this.rowCell, this.colCell, false);
    },

    bindTableEvents: function () {
        $('#' + this.tableName + ' thead tr th').bind('click', { context: this }, this.onTableHeaderClicked);
        $('#' + this.tableName + ' tbody tr td').bind('click', { context: this }, this.onTableRowClicked);
        $('#' + this.tableName + ' tbody tr').bind('dblclick', { context: this }, this.onTableDoubleClicked);
        $('#' + this.tableName + ' tbody tr').bind('keydown', { context: this }, this.onTableKeyDown);
        $('#' + this.saveId).bind('click', { context: this }, this.onTableSaveClicked);
        $('#' + this.addColumnId).bind('click', { context: this }, this.onAddColumnClicked);
    },
    //unbindTableEvents: function () {

    //    $('#' + this.addColumnId).unbind('click', { context: this }, this.onAddColumnClicked);
    //},
    onTableHeaderClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        self.colNum = parseInt($(this).index());
        console.log("column_num =" + self.colNum);
    },
    onTableRowClicked: function (ev) {
        var self = ev.data.context;
        self.colCell = parseInt($(this).index());
        self.rowCell = parseInt($(this).parent().index());
        console.log("Row_num =" + self.rowCell + "  ,  column_num =" + self.colCell);
    },
    restoreRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);

        for (var i = 0, iLen = jqTds.length ; i < iLen ; i++) {
            oTable.fnUpdate(aData[i], nRow, i, false);
        }
    },

    editRow: function (oTable, nRow) {
        debugger;
        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        jqTds[this.colCell].innerHTML = '<input type="text" id ="typ" value="' + aData[this.colsList[this.colCell].mData] + '"/>';
    },
    onTableDoubleClicked: function (e) {
        debugger;
        var self = e.data.context;
        e.preventDefault();
        var nRow = $(this)[0];
        var jqTds = $('>td', nRow);
        if ($.trim(jqTds[0].innerHTML.substr(0, 6)) != '<input') {
            if (self.inEditMode !== null && self.inEditMode != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                self.restoreRow(self.oTable, self.inEditMode);
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);

            }
            else {
                /* No edit in progress - let's start one */
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);
            }
        }
    },
    onTableKeyDown: function (ev) {
        var self = ev.data.context;
        if (ev.keyCode == 13) {
            ev.preventDefault();

            if (self.inEditMode == null)
                alert("Select Row");
            else
                self.saveRow(self.oTable, self.inEditMode);
            self.inEditMode = null;
        }
    },
    onAddColumnClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        self.colsList.splice(self.colNum + 1, 0, { "mDataProp": "newField" + self.iterator, sTitle: "Col-" + self.iterator, sType: "string" });
        //update the result, actual data to be displayed
        for (var iRes = 0; iRes < self.tableData.length ; iRes++) {
            self.tableData[iRes]["newField" + self.iterator] = "data-" + self.iterator;
        }
        //destroy the table
        self.dataTable.fnDestroy();
        $('#' + self.tableName + ' thead tr th').eq(self.colNum).after('<th>Col-' + self.iterator + '</th>');
        //init again
        self.setTable();
        self.iterator++;
    },

    onTableSaveClicked: function (ev) {
        var self = ev.data.context;
        var stop;
        var output = {};
        var table = $('#' + self.tableName).DataTable();
        var rows = $('#' + self.tableName + ' tr');
        var StopNames = [];
        var TripNumbers = [];
        var Trip = [];
        var TripDetails = [];
        StopNames = table.column(0).data().toArray();
        for (var i = 1; i < rows[0].cells.length; i++) {
            TripNumbers.push(rows[0].cells[i].innerText);
            Trip = table.column(i).data().toArray();
            TripDetails = TripDetails.concat(Trip);
        }
        var timeTable = {
            'StopNames': StopNames,
            'TripNumbers': TripNumbers,
            'TripDetails': TripDetails
        };

        $.ajax({
            type: "POST",
            url: "/ScheduleManagement/ScheduleManagement/MasterSaveSchedules",
            contentType: 'application/json;',
            dataType: "json",
            data: JSON.stringify(timeTable),
            success: function (values) {
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
}

我的mvc视图页面如下所示

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_MasterLayout.cshtml";
    
}
<script src="~/Content/Datatable/jquery-1.9.1.js"></script>
<script src="~/Content/Datatable/jquery.dataTables.js"></script>
<script src="~/Content/Datatable/jquery-ui.js"></script>
<script src="~/Content/Datatable/jquery.jeditable.js"></script>
<script src="~/Content/Datatable/jquery.dataTables.editable.js"></script>
<link href="~/Content/Datatable/jquery.dataTables.css" rel="stylesheet" />
<script src="~/Areas/ScheduleManagement/Scripts/TripDataTable.js"></script>

Select any col/row to add col/row after/below it<br/>
<button type="button" id="btnAddCol1">Add new column(Trip In)</button>
<button type="button" id="btnTrip1Save">Save Trip In</button>

<button type="button" id="btnAddCol2">Add new column(Trip Out)</button>
<button type="button" id="btnTrip2Save">Save Trip Out</button>
<br>
<table class="dataTable" id="tripInTable">
</table>
<br />
<table class="dataTable" id="tripOutTable">
</table>
<script type="text/javascript">
    $(document).ready(function () {
        var tripInTable = new triptable('tripInTable', '0', 'btnAddCol1', 'btnTrip1Save');
        var tripOutTable = new triptable('tripOutTable', '1', 'btnAddCol2', 'btnTrip2Save');
    });
</script>

请帮我解决这个问题

修复此问题:

function triptable(tablename, isTripIn, addColumnButton, saveButton) {
    this.tableName = tablename;
    this.istripin = isTripIn;
    this.dataTable = null;
    this.rowNum = 1;
    this.colNum = 0;
    this.rowCell = 0;
    this.colCell = 0;
    this.iterator = 0;
    this.colsList = [];
    this.tableData = [{}];
    this.oTable = null;
    this.inEditMode = null;
    this.addColumnId = addColumnButton;
    this.saveId = saveButton;
    this.init();
}

triptable.prototype = {
    init: function () {
        this.getSchedules();
    },
    getSchedules: function () {
        var req = $.ajax({
            type: "GET",
            url: "/ScheduleManagement/ScheduleManagement/GetSchedules/?id=" + this.istripin,
            dataType: "json",
            context: this,
        });

        req.done(function (result) {
            this.colsList = [];
            var returnedData = JSON.parse(result);
            if (returnedData.length > 0) {
                var obj = returnedData[0];
                for (var key in obj) {
                    var attrName = key;
                    var attrValue = obj[key];
                    var column = {
                        "mData": key,
                        "mDataProp": key,
                        "sTitle": key,
                        "sType": "string"
                    };
                    this.colsList.push(column);
                }
                results = returnedData;
                var stop = this.colsList[this.colsList.length - 1];
                var i = this.colsList.indexOf(stop);
                if (i != -1) {
                    this.colsList.splice(i, 1);
                }

                this.colsList.unshift(stop);
                this.colNum = this.colsList.length;
                this.tableData = returnedData;
                this.setTable();
                this.oTable = this.dataTable;
            }
        });
    },
    setTable: function () {
        //Construct the measurement table
        this.dataTable = $('#' + this.tableName).dataTable({
            "bJQueryUI": true,
            "bDeferRender": true,
            "bInfo": false,
            "bSort": false,
            "bDestroy": true,
            "bFilter": false,
            "bPagination": false,
            "aaData": this.tableData,
            "aoColumns": this.colsList,
        });

        this.bindTableEvents(this);
    },

    saveRow: function (oTable, nRow) {
        var jqInputs = $('input', nRow);
        oTable.fnUpdate(jqInputs[0].value, this.rowCell, this.colCell, false);
    },

    unbindTableEvents: function (contextData) {
        $('#' + contextData.tableName + ' thead tr th').off('click', contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').off('click', contextData.onTableRowClicked);
        $('#' + contextData.tableName + ' tbody tr').off('dblclick', contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').off('keydown', contextData.onTableKeyDown);
        $('#' + contextData.saveId).off('click', contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).off('click', contextData.onAddColumnClicked);
    },
    bindTableEvents: function (contextData) {
        contextData.unbindTableEvents(contextData);
        $('#' + contextData.tableName + ' thead tr th').on('click', { context: contextData }, contextData.onTableHeaderClicked);
        $('#' + contextData.tableName + ' tbody tr td').on('click', { context: contextData }, contextData.onTableRowClicked);
        $('#' + contextData.tableName + ' tbody tr').on('dblclick', { context: contextData }, contextData.onTableDoubleClicked);
        $('#' + contextData.tableName + ' tbody tr').on('keydown', { context: contextData }, contextData.onTableKeyDown);
        $('#' + contextData.saveId).on('click', { context: contextData }, contextData.onTableSaveClicked);
        $('#' + contextData.addColumnId).on('click', { context: contextData }, contextData.onAddColumnClicked);
    },

    onTableHeaderClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        self.colNum = parseInt($(this).index());
        console.log("column_num =" + self.colNum);
    },
    onTableRowClicked: function (ev) {
        var self = ev.data.context;
        self.colCell = parseInt($(this).index());
        self.rowCell = parseInt($(this).parent().index());
        console.log("Row_num =" + self.rowCell + "  ,  column_num =" + self.colCell);
    },
    restoreRow: function (oTable, nRow) {

        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);

        for (var i = 0, iLen = jqTds.length ; i < iLen ; i++) {
            oTable.fnUpdate(aData[i], nRow, i, false);
        }
    },

    editRow: function (oTable, nRow) {
        debugger;
        var aData = oTable.fnGetData(nRow);
        var jqTds = $('>td', nRow);
        jqTds[this.colCell].innerHTML = '<input type="text" id ="typ" value="' + aData[this.colsList[this.colCell].mData] + '"/>';
    },
    onTableDoubleClicked: function (e) {
        debugger;
        var self = e.data.context;
        e.preventDefault();
        var nRow = $(this)[0];
        var jqTds = $('>td', nRow);
        if ($.trim(jqTds[0].innerHTML.substr(0, 6)) != '<input') {
            if (self.inEditMode !== null && self.inEditMode != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                self.restoreRow(self.oTable, self.inEditMode);
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);

            }
            else {
                /* No edit in progress - let's start one */
                self.inEditMode = nRow;
                self.editRow(self.oTable, nRow);
            }
        }
    },
    onTableKeyDown: function (ev) {
        var self = ev.data.context;
        if (ev.keyCode == 13) {
            ev.preventDefault();

            if (self.inEditMode == null)
                alert("Select Row");
            else
                self.saveRow(self.oTable, self.inEditMode);
            self.inEditMode = null;
        }
    },
    onAddColumnClicked: function (ev) {
        debugger;
        var self = ev.data.context;
        self.colsList.splice(self.colNum + 1, 0, { "mDataProp": "newField" + self.iterator, sTitle: "Col-" + self.iterator, sType: "string" });
        //update the result, actual data to be displayed
        for (var iRes = 0; iRes < self.tableData.length ; iRes++) {
            self.tableData[iRes]["newField" + self.iterator] = "data-" + self.iterator;
        }
        //destroy the table
        self.dataTable.fnDestroy();
        $('#' + self.tableName + ' thead tr th').eq(self.colNum).after('<th>Col-' + self.iterator + '</th>');
        //init again
        self.setTable();
        self.iterator++;
        self.bindTableEvents(self);
    },

    onTableSaveClicked: function (ev) {
        var self = ev.data.context;
        var stop;
        var output = {};
        var table = $('#' + self.tableName).DataTable();
        var rows = $('#' + self.tableName + ' tr');
        var StopNames = [];
        var TripNumbers = [];
        var Trip = [];
        var TripDetails = [];
        StopNames = table.column(0).data().toArray();
        debugger;
        for (var i = 1; i < rows[0].cells.length; i++) {
            var trip = (rows[0].cells[i].innerText).replace(/\\n/g, '');
            TripNumbers.push(trip);
            Trip = table.column(i).data().toArray();
            var str = Trip.join("&");
            str = str.replace(/\s+/g, '');
            TripDetails.push(str);
        }
        var timeTable = {
            'StopNames': StopNames,
            'TripNumbers': TripNumbers,
            'TripDetails': TripDetails
        };

        $.ajax({
            type: "POST",
            url: "/ScheduleManagement/ScheduleManagement/MasterSaveSchedules",
            contentType: 'application/json;',
            dataType: "json",
            data: JSON.stringify(timeTable),
            success: function (values) {
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
}

0 个答案:

没有答案