JQuery Datatables editor 本地编辑功能

背景

很多项目需求中,不需要表格自己进行AJax操作,数据的交互需要另外写代码实现,表格只需要提供本地编辑即可,这该怎么办呢?其实editor对这种实现很简单,去掉editor中的ajax属性即可可以点击这里查看editor官方网站对本地编辑的说明

我调用上一篇文章中的代码作为演示,代码有点长,只需要看到我注释了editor中的ajax属性即可:

    $(document).ready(function () {

        editor = new $.fn.dataTable.Editor({
            //ajax: {
            //    create: {
            //        url: "/Home/AddData",
            //        type: "Post",
            //        dataType: "json",
            //        data: function (data) {
            //            var Person = {};
            //            var id;
            //            mydata = data.data;
            //            for (var key in mydata)
            //            {
            //                console.log("check create row id:" + key);
            //                id = key;
            //            }
            //            if (key == "0")//新增模式
            //            {
            //                console.log("entry create mode:");
            //                Person.Name = mydata[0].Name;
            //                Person.Position = mydata[0].Position;
            //                Person.Office = mydata[0].Office;
            //                Person.Age = mydata[0].Age;
            //                Person.Salary = mydata[0].Salary;
            //                Person.Gender = mydata[0].Gender;
            //                Person.Level = mydata[0].Level;
            //                Person.Date = mydata[0].Date;
            //            }
            //            else {//复制模式
            //                console.log("entry duplicate mode:");
            //                Person.Name = mydata[id].Name;
            //                Person.Position = mydata[id].Position;
            //                Person.Office = mydata[id].Office;
            //                Person.Age = mydata[id].Age;
            //                Person.Salary = mydata[id].Salary;
            //                Person.Gender = mydata[id].Gender;
            //                Person.Level = mydata[id].Level;
            //                Person.Date = mydata[id].Date;
            //            }
            //            return Person;
            //        },
            //        success: function (json) {
            //            var DT_RowId = GetRandomRowID();
            //            console.log('new row id:' + DT_RowId);//前台打印DT_RowId
            //            json.data[0].DT_RowId = DT_RowId;//对新增的数据生成随机字符串作为主键
            //        },
            //    },
            //    edit: {
            //        type: 'Post',
            //        url: '/Home/UpdataData',
            //        dataType: 'json',
            //        data: function (data) {
            //            var returndata = { data: [] };
            //            var DT_RowId;
            //            var datas = data.data;
            //            for (var key in datas)
            //            {
            //                console.log('editor row id:'+ key);//前台打印DT_RowId
            //                DT_RowId = key;//获取DT_RowId
            //                var mydata = datas[DT_RowId];
            //                var data = {};
            //                data.DT_RowId = DT_RowId;
            //                data.Name = mydata.Name;
            //                data.Position = mydata.Position;
            //                data.Office = mydata.Office;
            //                data.Age = mydata.Age;
            //                data.Salary = mydata.Salary;
            //                data.Gender = mydata.Gender;
            //                data.Level = mydata.Level;
            //                data.Date = mydata.Date;
            //                returndata.data.push(data);
            //            }
            //            return returndata;

            //        },
            //        success: function (json) {
            //            //var returnData = {};
            //            //returnData.data = json.data;
            //            //return returnData;
            //        },
            //    },
            //    remove: {
            //        url: '/Home/DeleteData',
            //        type: 'Post',
            //        dataType: "json",
            //        data: function (data) {
            //            var returndata = {data:[]};
            //            var DT_RowId;
            //            var datas = data.data;
            //            for (var key in datas) {
            //                console.log('remove row id:' + key);//前台打印DT_RowId
            //                DT_RowId = key;//获取DT_RowId

            //                var mydata = datas[DT_RowId];
            //                var data = {};
            //                data.DT_RowId = DT_RowId;
            //                data.Name = mydata.Name;
            //                data.Position = mydata.Position;
            //                data.Office = mydata.Office;
            //                data.Age = mydata.Age;
            //                data.Salary = mydata.Salary;
            //                data.Gender = mydata.Gender;
            //                data.Level = mydata.Level;
            //                data.Date = mydata.Date;
            //                returndata.data.push(data);
            //            }
            //            //var returndata = JSON.stringify(Persons)
            //            return returndata;
            //        },
            //        success: function (json) {
            //            //return json;
            //        },
            //    }

            //},
            table: "#example",
            //idSrc: 'Name',
            fields: [
                { label: "Name", name: "Name" },
                { label: "Position", name: "Position", multiEditable: false },//multiEditable:无法进行批量编辑
                { label: "Office", name: "Office" },
                { label: "Age", name: "Age" },
                { label: "Salary", name: "Salary" },
                {
                    label: "Gender", name: "Gender", type: "radio",
                    options: [
                        { label: "男", value: "1" },
                        { label: "女", value: "0" },
                    ],
                    def:"1"
                },
                {
                    label: "Level", name: "Level", type: "select",
                    options: [
                        { label: "1(highest)", value: "1" },
                        { label: "2", value: "2" },
                        { label: "3", value: "3" },
                        { label: "4", value: "4" },
                        { label: "5(lowest)", value: "5" },
                    ],
                    def:"1"                   
                },
                {
                    label: "Date", name: "Date", type: "datetime",
                    def: function () { return new Date(); },
                    fieldInfo: '请选择时间',
                    keyInput: false, //禁止用户手动输入
                }

            ],
            i18n: {
                create: {
                    button: "新建",
                    title: "新增数据",
                    submit: "保存"
                },
                edit: {
                    button: "编辑",
                    title: "修改数据",
                    submit: "保存修改"
                },
                remove: {
                    button: "删除",
                    title: "删除数据",
                    submit: "删除",
                    confirm: {
                        _: "确定删除这 %d 几行数据?",
                        1: "确定删除这一行数据?"
                    }
                },
                error: {
                    system: "服务器或网络发生错误,请联系系统管理员或稍后再试..."
                },
                datetime: {
                    previous: '上一页',
                    next: '下一页',
                    months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                    weekdays: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
                }
            }
        });

        table = $('#example').DataTable({
            ajax: {
                url: "/Home/GetData",
                type: "Get",
                dataType: "json",
                data: {

                },
                dataSrc: function (json) {
                    $.each(json, function (k, v) {
                        v.DT_RowId = GetRandomRowID();//在前端对服务端返回的数据生成随机字符串作为主键
                    });
                    return json;
                },
                error: function () {
                    alert("服务器未正常响应,请重试");
                },
            },
            dom: 'Bfrtip',
            select: {
                style: 'os',
                selector: 'td:first-child'
            },
            buttons: [
                {
                    extend: "create",
                    editor: editor,
                    formButtons: [
                        "新增",
                        { text: "取消", action: function () { this.close();}}
                    ]
                },
                //{
                //    extend: "edit",//原编辑功能代码
                //    editor: editor,
                //    formButtons: [
                //        "修改",
                //        { text: "取消", action: function () { this.close(); }}
                //    ]
                //},
                {
                    extend: 'selected',
                    text: '编辑',
                    action: function () {
                        var indexes = table.rows({ selected: true }).indexes();

                        editor.edit(indexes, {
                            title: '编辑',
                            buttons: indexes.length === 1 ?
                                backNext :
                                '保存'
                        });
                    }
                },
                {
                    extend: "remove",
                    editor: editor,
                    formButtons: [
                        "删除",
                        { text: "取消", action: function () { this.close();}}
                    ]
                },
                {
                    extend: "selected",
                    text: '复制',
                    action: function (e, dt, node, config) {
                        // Start in edit mode, and then change to create
                        editor
                            .edit(table.rows({ selected: true }).indexes(), {
                                title: '复制原数据',
                                buttons: '新增复制'
                            })
                            .mode('create');
                    }
                },
            ],
            columns: [
                {
                    data: null,
                    defaultContent: '',
                    orderable: false,
                    className: 'select-checkbox',
                },
                { title: "Name", data: "Name"},
                { title: "Position", data: "Position",className:"canEditor"},
                { title: "Office", data: "Office",className:"canEditor"},
                { title: "Age", data: "Age",className: "canEditor" },
                { title: "Salary", data: "Salary", className: "canEditor" },
                {
                    title: "Gender", data: "Gender", className: "canEditor",
                    render: function (val, type, row) {
                        return val == "1" ? "男" : "女";
                    }
                },
                { title: "Level", data: "Level", className: "canEditor dt-body-center" },
                { title: "Date", data: "Date", className: "canEditor",}

            ],
            language: {
                processing: "正在获取数据,请稍后...",
                search: "搜索",
                lengthMenu: "显示 _MENU_ 条",
                info: "当前显示的第是 _START_ 到 _END_ 行数据,共 _TOTAL_ 行数据",
                infoEmpty: "记录数为0",
                infoFiltered: "((全部记录数 _MAX_ 条))",
                infoPostFix: "",
                loadingRecords: "系统处理中,请稍等...",
                zeroRecords: "没有您要搜索的内容",
                emptyTable: "没有数据",
                paginate: {
                    first: "第一页",
                    previous: "上一页",
                    next: "下一页",
                    last: "最后一页"
                },
                aria: {
                    sortAscending: "以升序排列此列",
                    sortDescending: "以降序排列此列"
                }
            }
        });

        editor.on('preSubmit', function (e, o, action) {
            if (action !== 'remove') {
                var firstName = this.field('Name');

                // Only validate user input values - different values indicate that
                // the end user has not entered a value
                if (!firstName.isMultiValue()) {
                    if (!firstName.val()) {
                        firstName.error('Name不能为空');
                    }

                    if (firstName.val().length >= 20) {
                        firstName.error('Name不能超过20个字母!');
                    }
                }

                // ... additional validation rules

                // If any error was reported, cancel the submission so it can be corrected
                if (this.inError()) {
                    return false;
                }
            }
        });

        // Buttons array definition to create previous, save and next buttons in
        // an Editor form
        var backNext = [
            {
                text: "<",
                action: function (e) {
                    // On submit, find the currently selected row and select the previous one
                    this.submit(function () {
                        var indexes = table.rows({ search: 'applied' }).indexes();
                        var currentIndex = table.row({ selected: true }).index();
                        var currentPosition = indexes.indexOf(currentIndex);

                        if (currentPosition > 0) {
                            table.row(currentIndex).deselect();
                            table.row(indexes[currentPosition - 1]).select();
                        }

                        // Trigger editing through the button
                        table.button(1).trigger();
                    }, null, null, false);
                }
            },
            '保存',
            {
                text: ">",
                action: function (e) {
                    // On submit, find the currently selected row and select the next one
                    this.submit(function () {
                        var indexes = table.rows({ search: 'applied' }).indexes();
                        var currentIndex = table.row({ selected: true }).index();
                        var currentPosition = indexes.indexOf(currentIndex);

                        if (currentPosition < indexes.length - 1) {
                            table.row(currentIndex).deselect();
                            table.row(indexes[currentPosition + 1]).select();
                        }

                        // Trigger editing through the button
                        table.button(1).trigger();
                    }, null, null, false);
                }
            }
        ];
    });

去掉ajax属性后,每次新增数据,editor便会调用自己的内部的方法对新增行生成一个唯一的(id)主键,存放在DT_RowId字段中,以便接下去的可以对数据进行编辑和删除操作。可以通过如下方法获取每行的DT_RowId的值:

var id = table.row(editCurrentRow).id();//获取DT_RowId的值,editCurrentRow为行号

 

 

上一篇:文本特征提取


下一篇:0007 输出以下图形