jQuery tableGrid插件(原创并附加代码)

    随着网络应用的不断发展,用户对富客户端的要求越来越完美,一个完美的界面操作往往可以将一个服务端数据展示的完美

 

    这几年来,jQuery一直是我热捧的javascript库,简单易懂,操作方便,无聊的时候就喜欢写一些控件,今天展示下

 tableGrid控件(非完整版)

 

 

    控件中有行编辑(面前有combox,timepick,checkbox,text4种编辑类型),列排序,自定义button,自定义xtype型编辑框,自定义列模式 (3种供选择),这些是我现在展示的代码中所拥有的功能(非完整版)。在完整版中还有行拖拽,列进度条显示,分页条进度条模式等等

 

    先来看看效果:

   
jQuery tableGrid插件(原创并附加代码)_第1张图片

 

 

   为了对数组和对象操作更加方便,仿java编写了一个map方法,代码如下:

 

function Map() {
    this.isMap = true;
    var struct = function (key, value, other) {
        this.key = key;
        this.value = value;
        this.other = other;
    };
    var put = function (key, value, other) {
        for (var i = 0; i < this.arr.length; i++) {
            if (this.arr[i].key === key) {
                if (typeof other == Boolean || other === true) {
                    this.arr[i].value += "," + value;
                } else {
                    this.arr[i].value = value;
                    this.arr[i].reg = other;
                }
                return;
            }
        }
        this.arr[this.arr.length] = new struct(key, value, other);
    };


    var getOtherVal = function (key) {
        for (var i = 0; i < this.arr.length; i++)  if (this.arr[i].key === key) return this.arr[i].other;
        return null;
    };

    var getValue = function (key) {
        for (var i = 0; i < this.arr.length; i++)  if (this.arr[i].key === key) return this.arr[i].value;
        return null;
    };

    var remove = function (key) {
        var v;
        for (var i = 0; i < this.arr.length; i++) {
            v = this.arr.pop();
            if (v.key === key) continue;
            this.arr.unshift(v);
        }
    };
    var keySet = function () {
        var keyArr = [];
        for (var i = 0; i < this.arr.length; i++) {
            var _key = this.arr[i].key;
            keyArr[i] = _key;
        }
        return keyArr;
    };
    var valSet = function () {
        var valArr = [];
        for (var i = 0; i < this.arr.length; i++) {
            var _val = this.arr[i].value;
            valArr[i] = _val;
        }
        return valArr;
    };
    var alertKeyAndVal = function () {
        var store = "";
        for (var i = 0; i < this.arr.length; i++) {
            var _val = this.arr[i].key;
            var _key = this.arr[i].value;
            store += "key:" + _key + ",val:" + _val;
        }
        return store;
    };
    var size = function () {
        return this.arr.length;
    };
    var isEmpty = function () {
        return this.arr.length <= 0;
    };

    this.arr = new Array();
    this.getValue = getValue;
    this.getOtherVal = getOtherVal;
    this.put = put;
    this.remove = remove;
    this.size = size;
    this.isEmpty = isEmpty;
    this.keySet = keySet;
    this.valSet = valSet;
    this.alertKeyAndVal = alertKeyAndVal;
}
 

 

    再展示下jquery.tableGrid.js文件:

 

function Store(ps) {
    this.url = ps.url;
    this.JsonReader = ps.JsonReader;
    var getUrl = function() {
        return this.url;
    }
    var getReader = function() {
        return this.JsonReader;
    }
    this.getUrl = getUrl;
    this.getReader = getReader;
}
(function ($) {
    $.fn.grid = $.grid = function (opt) {
        var ps = $.extend({}, $.fn.grid.defaults, opt || {});
        $.fn.grid.defaults = {
            ele:'grid',
            width:'650px',
            selModel:'CheckModel',
            dblUpdate:false,
            async:true,
            subJoin:'',
            colModel:[],
            method:'post',
            dataType:'json',
            titleBar:'',
            rowHeight:27,
            onClickRowEvent:function() {
            },
            toolBar:[],
            PagingToolbar:{},
            UpdataModel:{},
            updataModel:"td",
            hasBotton:false
        };

        var grid = this;
        this.hideTd = new Map();
        this.columSelectMap = new Map();
        this.columCheckMap = new Map();
        this.columFunMap = new Map();
        this.columProgressMap = new Map();
        this.toolbarMap = new Map();
        this.totalMap = new Map();
        this.rowHeight = ps.rowHeight;
        this.disp = 0;
        this.data = [];
        this.widthArr = [];
        this.RowData = [];
        this.ajaxdata;
        this.saveUrl = ps.UpdataModel.SaveUrl;
        this.findSortKey;

        ps.width.substring(ps.width.length - 1) == "%" ? this.widthtype = true : this.widthtype = false;
        var removeArr = ['pFirst pFirstd','pPrev pPrevd','pNext pNextd','pLast pLastd','pFirstd','pPrevd','pNextd','pLastd','pFirst','pPrev','pNext','pLast'];
        var fun = {
            estimateBrowser: function() {
                var Sys = {};
                var ua = navigator.userAgent.toLowerCase();
                var s;
                (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
                return Sys;
            },
            createBody:function(grid) {
                grid.filterDiv = $('<div class="nBtn" style="left: 229px; top: 53px;"><div></div></div>').hide().appendTo(grid);
            },

            cssOperate:function(obj, css1, css2) {
                obj.addClass(css1).removeClass(css2);
            },

            sortFun:function(rows, newDirection, oTable, column, flag) {
                $.each(rows, function(index, row) {
                    if (flag)
                        row.sortKey = parseInt(grid.findSortKey($(row).find("td").eq(column)));
                    else
                        row.sortKey = grid.findSortKey($(row).find("td").eq(column));
                });
                rows.sort(function(a, b) {
                    if (a.sortKey < b.sortKey) {
                        return -newDirection;
                    } else if (a.sortKey > b.sortKey) {
                        return newDirection;
                    } else {
                        return 0;
                    }

                });
                $.each(rows, function(index, row) {
                    oTable.children("tbody").append(row);
                    row.sortKey = null;
                });
            },

            createTitle:function(grid) {
                if (ps.titleBar != '') {
                    grid.TitleHeight = 26;
                    var ftitle = document.createElement('div');
                    var ptogtitle = document.createElement('div');
                    $(fun.mDiv).addClass('mDiv').appendTo(grid);
                    $(ftitle).addClass('ftitle').html('<span>' + ps.titleBar + '</span>').appendTo(fun.mDiv);
                }
            },

            createHr:function(grid) {
                grid.total = false;
                grid.HrHeight = 26;
                var hTable = document.createElement('table');
                $(fun.hDiv).addClass('hDiv').appendTo(grid);
                var hrTitle = [];
                hrTitle.push(' <tbody> <tr style="height:', 21, '" class="dataTableHead">');

                if (ps.selModel == 'CheckModel' || ps.selModel == 'TdSelectionModel') {
                    if (grid.widthtype) hrTitle.push('<th class="checkbox sorted" width="33px" index="0">')
                    else hrTitle.push('<th class="grid-th checkbox sorted" width="33px" index="0">');
                    hrTitle.push('  <div align="center" style="overflow:hidden;"> <input type="checkbox" name="checkbox[]"/></div>');
                    hrTitle.push('</th>');
                } else if (ps.selModel == 'RowSelectionModel') {
                    if (grid.widthtype) hrTitle.push('<th index="0" class="rownumber sorted" width="33px"><div style="  overflow:hidden;"></div></th>');
                    else hrTitle.push('<th index="0" class="grid-th rownumber sorted" width="33px"><div style="  overflow:hidden;"></div></th>');
                }

                if (ps.subJoin == "RowIndexModel") {
                    if (grid.widthtype) hrTitle.push('<th index="0" class="grid-th rownumber sorted" width="33px" align="left">编号</th>');
                    else hrTitle.push('<th index="0" class="grid-th rownumber sorted" width="33px" align="left">编号</th>');
                }

                for (var i = 0; i < ps.colModel.length; i++) {
                    var _class = '' , _hide = '' , _sorts = '';
                    if (i == 0) _class = 'sorted';
                    var col = ps.colModel[i];

                    if (col.total) {
                        grid.total = true;
                        grid.totalMap.put(col.name, col.total);
                    }
                    if (col.hide) {
                        _hide = 'none';
                        grid.hideTd.put(col.name, col.name)
                    }
                    if (col.sort) {
                        _sorts = 'sort'
                    }

                    var width;

                    if (col.width.toString().substring(col.width.toString().length - 2) == "px") {
                        width = parseInt(col.width.toString().substring(0, col.width.toString().length - 2));
                    } else {
                        width = col.width;
                    }
                    grid.widthArr[i] = width;
                    hrTitle.push('<th index="', i + 1, '" sort="', _sorts, '" class="grid-th ', col.sort, '" width="', width, '" name="', col.name, '" class="', _class, '" style="display:', _hide, ';position:static ;">');
                    hrTitle.push('<div style="text-align: ' + col.align + ';  overflow:hidden;">' + col.display + '</div>');
                    hrTitle.push('</th>');
                }
                hrTitle.push('  </tr></tbody>');
                $(hTable).addClass('dataTable');
                $(hrTitle.join("")).appendTo(hTable);
                $(hTable).width("100%").attr('cellpadding', 0).attr('cellspacing', 0).appendTo(fun.hDiv);

                $("input[name='checkbox[]']", $(fun.hDiv)).click(function() {
                    $(this).attr("checked") == true ? grid.selectedRowByIndex() : grid.unselectedRowByIndex();
                });

                $("th:gt(0)", hTable).hover(function() {
//                    $(this).find("a").show();
                }, function() {
//                    $(this).find("a").hide();
                });

                $("th[sort='sort']", hTable).each(function() {
                    var th = $(this);
                    var column = th.attr("index");
                    if ($(this).hasClass("string")) {
                        grid.findSortKey = function($cell) {
                            return $cell.find("div").html();
                        }
                    }
                    else if ($(this).hasClass("num")) {
                        grid.findSortKey = function($cell) {
                            var key = parseInt($cell.find("div").html());
                            return isNaN(key) ? 0 : parseInt(key);
                        }
                    }
                    else if ($(this).hasClass("data")) {
                        grid.findSortKey = function($cell) {
                            return Date.parse('1 ' + $cell.find("div").html());
                        }
                    }
                    th.click(function() {
                        if (grid.findSortKey) {
                            var oTable = $('table', fun.bDiv);
                            var aTRs = new Array;

                            var newDirection = 1;
                            var rows = oTable.find("tbody > tr").get();
                            if ($(this).hasClass(".sorted-asc") || (!$(this).hasClass(".sorted-asc") && !$(this).hasClass(".sorted-desc"))) {
                                if ($(this).hasClass(".sorted-asc")) {
                                    newDirection = -1;
                                    fun.sortFun(rows, newDirection, oTable, column, $(this).hasClass("num"));
                                    $(this).removeClass("sorted-asc").addClass("sorted-desc");
                                    fun.cssOperate($(this), "sorted-desc", "sorted-asc");
                                    fun.cssOperate($(this).find("div"), "up", "dn");
                                } else if (!$(this).hasClass(".sorted-asc") && !$(this).hasClass(".sorted-desc")) {
                                    newDirection = 1;
                                    fun.sortFun(rows, newDirection, oTable, column, $(this).hasClass("num"));
                                    $(this).addClass("sorted-asc");
                                    fun.cssOperate($(this).find("div"), "dn", "up");
                                }
                            }
                            else if ($(this).hasClass(".sorted-desc")) {
                                $.each(grid.rawtype, function(index, row) {
                                    oTable.children("tbody").append(row);
                                    row.sortKey = null;
                                });
                                $(this).removeClass("sorted-desc").find("div").removeClass("dn up");
                            }
                        }
                        oTable.find("tbody > tr").removeClass('erow').each(function(index, n) {
                            if (index % 2 && ps.stripe) $(this).addClass('erow');
                        });

                        $(this).siblings().find("div").removeClass("dn up");
                    }).hover(function() {
                        $(this).addClass("hover");
                    }, function() {
                        $(this).removeClass("hover");
                    });
                })
            },

            createGbody:function(grid) {
                grid.bTable = document.createElement('table');
                grid.bTable.className = 'dataTable';
                grid.tbody = document.createElement('tbody');
//                $(fun.bDiv).height(ps.PagingToolbar.pageSize * 27 - 1).addClass('bDiv').appendTo(grid);
                $(fun.bDiv).height(ps.PagingToolbar.pageSize * 27 - 1).addClass('bDiv').appendTo(grid);
                grid.pageSize = ps.PagingToolbar.pageSize;
                var Store = ps.PagingToolbar.store;
                grid.url = Store.getUrl();
                grid.page = 1;
                grid.ajaxdata = Store.data;

                for (var i = 0; i < ps.PagingToolbar.pageSize; i++) {
                    var tr = document.createElement('tr');
                    var $tr = $(tr).appendTo(grid.tbody);
                    var td = document.createElement('td');

                    if (ps.selModel == 'CheckModel' || ps.selModel == 'TdSelectionModel') {
                        $(td).css({'padding-top':'2px'}).appendTo(tr);
                        $('<div style="text-align: center;  overflow:hidden;"><input type="checkbox" name="' + i + '"/></div>').click(function() {
                            if (ps.selModel == 'TdSelectionModel') {
                            }
                            else $(this).attr("checked") == true ? $(this).parent().parent().addClass('trSelected') : $(this).parent().parent().removeClass('trSelected');
                        }).appendTo(td);

                        if (ps.subJoin == "RowIndexModel") $(td).appendTo(tr);
                    } else if (ps.selModel == 'RowSelectionModel') {
                        $(td).css({'padding-top':'2px'}).appendTo(tr);
                    }

                    $(td).width('33px').attr('align', 'center');

                    for (var j = 0; j < ps.colModel.length; j++) {
                        var col = ps.colModel[j];
                        var widthStr = "";
                        var td = $('<td width=' + grid.widthArr[j] + ' align=' + col.align + '><div class="td" style="text-align: ' + col.align + ';  overflow:hidden;"></div></td>')
                        if (col.checkModel) {
                            grid.columCheckMap.put(col.name, j)
                        } else if (typeof col.selectModel != 'undefined') {
                            grid.columSelectMap.put(col.name, j);
                            $(td).attr({'selecter':true,'key':col.key});
                        } else if (jQuery.isFunction(col.renderer)) {
                            grid.columFunMap.put(col.name, j)
                        } else if (col.progressBarModel) {
                            grid.columProgressMap.put(col.name, j);
                        }

                        if (col.total == 'int' || col.total == 'float') {
                            $(td).attr('total', col.total);
                        }

                        $(td).click(function() {
                            var $tr = $(this).parent();
                            if (ps.selModel == 'TdSelectionModel') {
                                $tr.siblings().find('td:eq(0)').find('input').attr('checked', false);
                                grid.getAllTdObj().not($(this).addClass('tdSelected')).removeClass('tdSelected')
                            } else {
                                var $sibings = $tr.addClass('trSelected').siblings().removeClass('trSelected').find('td:eq(0)').find('input').attr('checked', false);
                            }
                            $('td:eq(0)', $tr).find('input').attr('checked', true);
                        }).attr({
                            'name':col.name,
                            'editor':col.editor,
                            'editoring':'false',
                            'align':col.align
                        }).appendTo(tr);
                        if (grid.hideTd.getValue(col.name) != null) $(td).hide(); //.css('width',col.width)
                    }
                    grid.RowData[i] = $tr;
                    $tr.hide();
                }
                $("tr", $(grid.tbody)).click(function() {
                    var index = $(this).attr("index");
                    ps.onClickRowEvent(grid.data[index]);
                });
                fun.bind(grid.url, grid.ajaxdata, 1, true, grid);
                $(grid.tbody).appendTo(grid.bTable);
                $(grid.bTable).width("100%").attr('cellpadding', 0).attr('cellspacing', 0).appendTo(fun.bDiv);
                grid.getEditorsTd().attr("editored", "true");
            },


            createTotal:function(grid) {
                fun.tDiv.className = 'toDiv';
                var table = document.createElement('table');
                var total = [];
                total.push('  <tr style="height:26px;">');
                if (grid.widthtype)
                    total.push('<th width="3%">&nbsp;</th>');
                else
                    total.push('<th width="25">&nbsp;</th>');
                for (var i = 0; i < ps.colModel.length; i++) {
                    var _class = '', _hide = '';
                    if (i == 0) _class = 'sorted';
                    var col = ps.colModel[i];
                    if (col.hide) {
                        _hide = 'none'
                    }
                    if (col.total) {
                        total.push('<th total="total" width="' + col.width + '" name="' + col.name + '" class="' + _class + '" align="' + col.align + '" style="display:' + _hide + ';">0</th>');
                    } else {
                        total.push('<th width="' + col.width + '" name="' + col.name + '" class="' + _class + '" align="' + col.align + '" style="display:' + _hide + ';"></th>');
                    }
                }
                total.push('  </tr>');
                $(total.join("")).appendTo(table);
                $(table).width("100%").appendTo(fun.tDiv);
                $(fun.tDiv).appendTo(grid)
            },

            createBotton:function(grid) {
                var span = document.createElement('span');
                $(span).appendTo(fun.vGrip);
                $(fun.vGrip).addClass('vGrip').appendTo(grid);
            },

            dragStart:function(dragtype, e, obj) {
                if (dragtype == 'vresize') return {
                    sy: e.pageY,
                    sx: e.pageX
                };
            },

            createPager:function(grid) {
                fun.pDiv.className = 'pDiv';
                fun.pDiv.innerHTML = '<div class="pDiv2" style="width:"'+(parseInt(grid.width())-2)+'"px;margin-right:2px"></div>';
                var html = '<div class="pGroup"></div>' +
                           '<div class="pGroup">' +
                           '<div name="pFirst" class="pFirst pButton"><span></span></div>' +
                           '<div name="pPrev" class="pPrev pButton"><span></span></div>' +
                           '</div>' +
                           '<div class="btnseparator"></div>' +
                           '<div class="pGroup"><span class="pcontrol">第 <input disabled="disabled" class="input" style="margin-top:2px;" type="text" size="2" value="1" /> 页,共 <span class="count"> 1 </span>页</span></div>' +
                           '<div class="btnseparator"></div>' +
                           '<div class="pGroup">' +
                           '<div name="pNext" class="pNext pButton"><span></span></div>' +
                           '<div name="pLast" class="pLast pButton"><span></span></div>' +
                           '</div>' +
                           '<div class="btnseparator"></div>' +
                           '<div class="pGroup" style="float:right;"><span class="pcontrol">共检测到&nbsp;</span><span class="pcontrol countS">0</span><span class="pcontrol">&nbsp;条数据</span></div>';//共检测到10条数据
                $('div', fun.pDiv).html(html);
                $(fun.pDiv).appendTo(grid);

                $('div[name="pFirst"]', fun.pDiv).click(function() {
                    if (!$(this).hasClass("pFirstd")) {
                        fun.changePage('first')
                    }
                });
                $('div[name="pPrev"]', fun.pDiv).click(function() {
                    if (!$(this).hasClass("pPrevd")) {
                        fun.changePage('prev')
                    }
                });
                $('div[name="pNext"]', fun.pDiv).click(function() {
                    if (!$(this).hasClass("pNextd")) {
                        fun.changePage('next')
                    }
                });
                $('div[name="pLast"]', fun.pDiv).click(function() {
                    if (!$(this).hasClass("pLastd")) {
                        fun.changePage('last')
                    }
                });
                $('.pReload', fun.pDiv).click(function() {
                    fun.bind(grid.url, grid.ajaxdata, grid.page, false, grid)
                });
            },

            createToolbar:function(grid) {
                if (ps.toolBar.length != 0) {
                    grid.toolbarHeight = 26;
                    fun.tbDiv.className = 'tDiv';
                    var tDiv2 = document.createElement('div');
                    tDiv2.className = 'tDiv2';
                    $(tDiv2).appendTo(fun.tbDiv);
                    for (var i = 0; i < ps.toolBar.length; i++) {
                        var button = ps.toolBar[i];
                        var buttonarr = [];
                        if (button.xtype == 'button') {
                            buttonarr.push('<div id="' + button.id + '" class="fbutton" tip="' + button.tooltip + '">');
                            buttonarr.push('  <div>');
                            buttonarr.push('     <span><input type="image" src="' + button.iconCls + '" style="width:17px;height:17px;"/></span><span style="padding-left:1px;padding-top:5px">' + button.text + '</span>');
                            buttonarr.push('  </div>');
                            buttonarr.push('</div>');
                            var $but = $(buttonarr.join("")).appendTo(tDiv2);

                            $but.hover(function() {
                                $(this).addClass("fbOver");
                            }, function() {
                                $(this).removeClass("fbOver");
                            });
                            fun.buttonEvent(i, $but);
                            grid.toolbarMap.put(button.id, i);
                        } else if (button.xtype == 'text') {
                            $('<div class="input"><span>' + button.label + '  </span><input id="' + button.id + '"/></div>').appendTo(tDiv2);
                        } else if (button.xtype == 'tbseparator' || button == '-') {
                            $(tDiv2).append('<div class="toolber-btnseparator"></div>');
                        } else if (button.xtype == 'check') {
                            $('<div class="check"><span>' + button.label + '  </span><input type="checkbox" id="' + button.id + '"/></div>').appendTo(tDiv2);
                        } else if (button.xtype == "combox") {
                            var div = $('<div class="input"><span>' + button.label + '  </span><input id="' + button.id + '"/></div>').appendTo(tDiv2);
                            div.find('input').Jcombox(button.combox);
                        }
                    }
                    if (ps.titleBar == '') $(fun.tbDiv).css({'border-top':'1px solid #99BBE8'})
                    $(fun.tbDiv).appendTo(grid);
                }
            },


            buttonEvent:function(index, button) {
                button.click(function() {
                    ps.toolBar[index].handler();
                })
            },

            setData:function(row, colum, val, grid) {
                var map = new Map();
                map = grid.data[row];
                map.remove(colum);
                map.put(colum, val);
            },

            input:function(tr, index, centext, display, isArray) {
                if (index % 2 && ps.stripe) tr.eq(index).addClass('erow');
                var map = new Map();
                if (ps.selModel == 'CheckModel' || ps.selModel == 'TdSelectionModel') {
                    $('td:first input', tr).attr('checked', false);
                    if (ps.subJoin == "RowIndexModel") {
                        $('td:eq(1)', tr.eq(index)).html(((grid.page - 1) * ps.PagingToolbar.pageSize) + index + 1);
                    }
                } else if (ps.selModel == 'RowSelectionModel') {
                    $('td:first', tr.eq(index)).html(((grid.page - 1) * ps.PagingToolbar.pageSize) + index + 1);
                }
                var gt = 0;
                if (ps.subJoin == "RowIndexModel") {
                    gt = 1;
                } else {
                    gt = 0;
                }
                grid.RowData[index] = tr.eq(index);//...
                $('td:gt(' + gt + ')', tr.eq(index).attr('index', index).removeClass('trSelected').show()).each(function(i) {
                    if ($(this).attr('editor') == 'true')$(this).attr('editored', 'true');
                    var name = ps.colModel[i].name;
                    if (grid.columFunMap.getValue(name) != null) {
                        $("div", $(this)).html(ps.colModel[grid.columFunMap.getValue(name)].renderer(isArray ? centext.getValue(name) : centext[name], index));
                        map.put(name, isArray ? centext.getValue(name) : centext[name]);
                    } else if (grid.columCheckMap.getValue(name) != null) {
                        var ch = ps.colModel[grid.columCheckMap.getValue(name)].checkModel;
                        var yes = ch.yes;
                        var no = ch.no;
                        var ischeck;
                        isArray ? centext.getValue(name) : centext[name] == yes ? ischeck = "checked=true" : ischeck = "";
                        $("<input type='checkbox' " + ischeck + " name='checkbox_disabled'/>").attr("disabled", "true").appendTo($(this).find("div").html(""));
                        map.put(name, isArray ? centext.getValue(name) : centext[name]);
                    } else if (grid.columProgressMap.getValue(name) != null) {
                        var width = $(this).find("div").width() * (parseInt(centext[name]) / 100);
                        var tdiv = $('<div class="x-progress-inner"><div class="x-progress-bar" style="height: 16px; width: ' + (width - 3) + 'px;"><font color="#FFFFF" style=""></font></div></div>').appendTo($(this).find("div:eq(0)").html(""));
                        map.put(name, isArray ? centext.getValue(name) : centext[name]);
                    } else {
                        var dataType = ps.colModel[i].DType;
                        if (dataType == "date") {
                            var year,month,day,date,hours,minutes,seconds;
                            var time;
                            if (centext[name] != "" && centext[name] != null) {
                                $.each(centext[name], function(i, c) {
                                    switch (i) {
                                        case "date":date = c;break;
                                        case "day":day = c;break;
                                        case "hours":hours = c;break;
                                        case "minutes":minutes = c;break;
                                        case "month":month = c;break;
                                        case "seconds":seconds = c;break;
                                        case "year":year = c;break;
                                    }
                                });
                                time = parseInt(1900 + year) + "-" + parseInt(month + 1) + "-" + parseInt(day + 1) + " " + hours + ":" + minutes + ":" + seconds;
                            } else {
                                time = "——";
                            }
                            $(this).find("div").text(time);
                            map.put(name, time);
                        } else {
                            $(this).find("div").text(isArray ? centext.getValue(name) : centext[name]);
                            map.put(name, isArray ? centext.getValue(name) : centext[name]);
                        }
                    }

                    var tot = grid.totalMap.getValue(name);
                    if (tot != null) {
                        var val = isArray ? centext.getValue(name) : centext[name];
                        var value = $('th[name="' + name + '"]', $(fun.tDiv)).text();
                        var total = 0;
                        if (tot == 'int') {
                            total = parseInt(value) + parseInt(val);
                        } else if (tot == 'float') {
                            total = parseFloat(value) + parseFloat(val);
                        }
                        $('th[name="' + name + '"]', $(fun.tDiv)).text(total);
                    }
                });
                grid.data[index] = map;
                display++;
                return display;
            },

            addData:function(data, firstinit, internal) {
                var tr = $('tbody tr', fun.bDiv);
                if (!internal) {
                    var temp = 1;
                    $('th[total="total"]', $(fun.tDiv)).text(0);
                    $.each(data, function() {
                        grid.msgCount = data.totalProperty;
                        grid.pageCount = Math.ceil((grid.msgCount / grid.pageSize));
                        if (firstinit) {
                            grid.page = 1;
                            grid.pageCount == 0 || grid.pageCount == 1 ? fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[6],removeArr[7]]) : fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[10],removeArr[11]]);
                        }
                        $('.count', fun.pDiv).html(grid.pageCount);
                        $('.input', fun.pDiv).val(grid.page);
                        if (temp == 2) {
                            var display = 0;
                            $.each(data.root, function(index, centext) {
                                display = fun.input(tr, index, centext, display, false);
                            });
                            grid.display = display;
                            display == 0 ? $('.pPageStat', $(fun.pDiv)).html(ps.PagingToolbar.emptyMsg) : $('.pPageStat', $(fun.pDiv)).html('');
                            for (var dis = parseInt(display); dis < grid.pageSize; dis++) tr.eq(dis).hide();
                            grid.data = grid.data.slice(0, display);
                        }
                        temp++;
                    })
                } else {
                    var display = 0;
                    $.each(data, function(index, n) {
                        display = disp = fun.input(tr, index, n, display, true);
                    });
                    for (var dis = parseInt(display); dis < grid.pageSize; dis++) tr.eq(dis).hide();
                }
                $("input[name='checkbox[]']", $(fun.hDiv)).attr("checked", false);

                if (grid.page == grid.pageCount) {
                    fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[6],removeArr[7]])
                } else if (grid.page < grid.pageCount && grid.page != 1) {
                    fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[10],removeArr[11]])
                }
            },

            changePage:function(ctype) {
                if (ctype == "first") {
                    grid.page = 1;
                    fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[8],removeArr[9]]);
                } else if (ctype == "prev") {
                    if (grid.page > 1) {
                        grid.page == 2 ? fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[8],removeArr[9]]) : fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[10],removeArr[11]]);
                        grid.page = grid.page - 1;
                    } else {
                        fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[10],removeArr[1]]);
                    }
                } else if (ctype == "next") {
                    if (grid.page < grid.pageCount) {
                        (grid.page == grid.pageCount - 1) ? fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[6],removeArr[7]]) : fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[10],removeArr[11]]);
                        grid.page = grid.page + 1;
                    }
                } else if (ctype == "last") {
                    grid.page = grid.pageCount;
                    fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[6],removeArr[7]]);
                }
                $('.input', fun.pDiv).val(grid.page);
                fun.bind(grid.url, grid.ajaxdata, grid.page, false, grid);
            },

            changeCls:function(remover, add) {
                $('div[name="' + removeArr[8] + '"]', fun.pDiv).removeClass(remover[0]).addClass(add[0]);
                $('div[name="' + removeArr[9] + '"]', fun.pDiv).removeClass(remover[1]).addClass(add[1]);
                $('div[name="' + removeArr[10] + '"]', fun.pDiv).removeClass(remover[2]).addClass(add[2]);
                $('div[name="' + removeArr[11] + '"]', fun.pDiv).removeClass(remover[3]).addClass(add[3]);
            },

            createLoader:function(grid) {
                var bDivheight = $(fun.bDiv).height();
                var div = document.createElement('div');
                div.innerHTML = 'loading...';
                fun.mkDiv.className = 'loadmask';
                fun.lDiv.className = 'loadmask-msg';
                $(div).appendTo(fun.lDiv);
                $(fun.lDiv).appendTo("body");
            },

            TrsDblclick:function(grid) {
                if (ps.updataModel == "tr") {
                    var AllTrs = grid.getAllTrObj().dblclick(function() {
                        var editorTrs = $(this).attr("iseditor", "true").find('td:gt(0)').each(function(i, n) {
                            fun.TdDblclick($(this));
                        })
                    })
                } else {
                    grid.getAllTdObj().dblclick(function() {
                        var td = $(this);
                        td.parent().attr('iseditor', 'true');
                        if (td.attr("editor") == 'true') {
                            fun.TdDblclick(td);
                            td.parent().attr("iseditor", 'true');
                        }
                    })
                }
            },

            TdDblclick:function(ele) {
                if (ele.attr("editored") == 'true') {
                    var index = ele.parent().attr('index');
                    var text = ele.text();
                    var name = ele.attr('name');
                    var val = grid.data[index].getValue(name);
                    if (ele.attr('selecter')) {
                        var input = $("<input class=\"x-form-text x-form-field\"/>").attr("value", val);
                        if (fun.estimateBrowser().ie == '8.0')
                            input.css({
                                "width":parseInt(ele.width() - 30) + "px",
                                "height":15
                            });
                        else if (typeof fun.estimateBrowser().ie != 'undefined' && fun.estimateBrowser().ie != '8.0')
                            input.css({
                                "width":parseInt(ele.width() - 30) + "px",
                                "height":17
                            });
                        else
                            input.css({
                                "width":parseInt(ele.width() - 30) + "px",
                                "height":15
                            });
                        ele.attr("editored", "false").find("div").html("").append(input);
                        $(input).Jcombox(ps.colModel[grid.columSelectMap.getValue(name)].selectModel);
                    } else {
                        if (grid.columCheckMap.getValue(name) != null) {
                            ele.attr("editored", "false").find("input").attr("disabled", false);
                        } else {
                            var input = $("<input />").css({
                                "width":ele.width() - 30,
                                "height":18
                            }).attr("value", val);
                            ele.attr("editored", "false").find("div").html("").append(input);
                        }
                    }
                }
            },

            bind:function(url, data, pageIndex, firstinit, grid) {
                var _url = "";
                var _data;
                url.substring(url.length - 1) == "&" ? _url = url + 'pageIndex=' + pageIndex + '&pageSize=' + grid.pageSize : _url = url + '?pageIndex=' + pageIndex + '&pageSize=' + grid.pageSize;
                data == "" ? _data = "" : _data = data;
                $.ajax({
                    type: ps.method,
                    url: _url,
                    data:_data,
                    dataType: ps.dataType,
                    timeout:30000,
                    error:function(err) {
                        alert(err)
                    },
                    beforeSend: function() {
                        $(fun.lDiv).css({
                            top: $(fun.hDiv).offset().top + (parseInt(ps.PagingToolbar.pageSize * 30) - 30) / 2,
                            left:grid.offset().left + (grid.width() - 110) / 2
                        }).show();
                    },
                    complete: function() {
                        $(fun.lDiv).hide();
                        if (grid.pageCount == 0 || grid.pageCount == 1) {
                            fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[6],removeArr[7]]);
                        } else {
                            if (grid.page == 1) {
                                fun.changeCls(removeArr, [removeArr[4],removeArr[5],removeArr[10],removeArr[11]]);
                            } else if (grid.page > 1 && grid.page < grid.pageCount) {
                                fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[10],removeArr[11]]);
                            } else if (grid.page == grid.pageCount) {
                                fun.changeCls(removeArr, [removeArr[8],removeArr[9],removeArr[6],removeArr[7]]);
                            }
                        }
                        grid.rawtype = $('table', fun.bDiv).find("tbody > tr");
                        $(".countS", fun.pDiv).html(grid.msgCount);
                    },
                    success: function(data) {
                        grid.disp = fun.addData(data, firstinit);
                    },
                    error: function(data) {
                        fun.bDiv.find("table").find("tr").hide();
                    }
                });
            },

            hideTd:function(name) {
                $('td[name="' + name + '"]', $(fun.bDiv)).hide();
                $('th[name="' + name + '"]', $(fun.hDiv)).hide();
                $('div[name="' + name + '"]', $(fun.pDrag)).hide();
            },

            displayTd:function(name) {
                $('td[name="' + name + '"]', $(fun.bDiv)).show();
                $('th[name="' + name + '"]', $(fun.hDiv)).show();
                $('div[name="' + name + '"]', $(fun.pDrag)).show();
            }
        };


        this.selectedRowByIndex = function(index) {
            if (typeof index == "undefined") {
                $("tr", $(fun.bDiv)).addClass('trSelected').find("td:eq(0)").find('input').attr('checked', true);
            } else {
                $("tr[index='" + index + "']", $(fun.bDiv)).addClass('trSelected').find("td:eq(0)").find('input').attr('checked', true);
            }
        };

        this.unselectedRowByIndex = function(index) {
            if (typeof index == "undefined") {
                $("tr", $(fun.bDiv)).removeClass('trSelected').find("td:eq(0)").find('input').attr('checked', false);
            } else {
                $("tr[index='" + index + "']", $(fun.bDiv)).removeClass('trSelected').find("td:eq(0)").find('input').attr('checked', false);
            }
        };

        this.selectAll = function() {
            this.selectedRowByIndex();
        };

        this.evaluate = function(row, colum, valOfInput, Tdele) {
            var grid = this;
            var val;
            if (grid.columFunMap.getValue(colum) != null) {
                $("div", Tdele).html(ps.colModel[grid.columFunMap.getValue(colum)].renderer(valOfInput, row));
                val = valOfInput;
            } else if (grid.columCheckMap.getValue(colum) != null) {
                $("div", Tdele).find("input").attr("disabled", true);
                var ch = ps.colModel[grid.columCheckMap.getValue(colum)];
                Tdele.find("input").attr("checked") == true ? val = ch.checkModel.yes : val = ch.checkModel.no;
            } else if(grid.columSelectMap.getValue(colum) != null){
                val = $(Tdele.find("input")).attr("key");
                $("div", Tdele).html(valOfInput);
            } else {
                $("div", Tdele).html(valOfInput);
                val = valOfInput;
            }

            if (Tdele.attr('total') == 'int' || Tdele.attr('total') == 'float') {
                var data_val = grid.data[row].getValue(colum);
                var total_val = $('th[name="' + colum + '"]', $(fun.tDiv)).text();
                if (Tdele.attr('total') == 'int') {
                    $('th[name="' + colum + '"]', $(fun.tDiv)).text(parseInt(total_val) - parseInt(data_val) + parseInt(val));
                } else {
                    $('th[name="' + colum + '"]', $(fun.tDiv)).text(parseFloat(total_val) - parseFloat(data_val) + parseFloat(val));
                }
            }

            fun.setData(row, colum, val, grid);
            Tdele.attr("editored", "true");
             var sjon = "";
            typeof Tdele.attr("key") != "undefined" ? sjon = "\"" + Tdele.attr("key") + "\":\"" + val + "\"" : sjon = "\"" + Tdele.attr("name") + "\":\"" + val + "\"";
            return sjon;
        };

        this.saveEvent = function () {
            var returnStr;
            var grid = this;
            var saveby = ps.UpdataModel.saveby;
            var data = "[{";
            var trs = $(fun.bDiv).find("tr[iseditor='true']").each(function (_index, n) {
                var arr = [];
                var tr = $(this).attr("iseditor", "false");
                var index = grid.getRowNo(tr);
                for (var i = 0; i < saveby.length; i++) {

                    var val = grid.getRow(index).getValue(saveby[i]);
                    data = data + "\"" + saveby[i] + "\":\"" + val + "\",";

                }
                var map = new Map();
                var temp = 0;
                var tr_childrens = $(this).find("td[editor='true']").each(function (i) {
                    var thisTd = $(this);
                    var type = thisTd.attr("reg");
                    if (thisTd.attr("editored") == "false") {
                        var colum = thisTd.attr("name");
                        var input_val = thisTd.find("div").find("input").val();
                        arr[temp] = grid.evaluate(index, colum, input_val, thisTd);
                        temp ++;
                    }
                    thisTd.attr("editored", "true");
                });
                arr.length != 0 ? (data = data + arr + "},{") : "";
                var index = $(this).find("td:eq(0)").find("div").html();
                grid.data[index - 1] = map;
            });
            var source = data.substring(0, data.length - 2) + "]";
            if (source == "]") {
                $.JMessage("message4-" + ps.ele, "温馨提示:", "请您确定是否有信息需要保存", "question");
            } else {
                $.ajax({
                    type: "post",
                    url: grid.saveUrl,
                    data:'saveSource=' + source,
                    timeout:30000,
                    async:false,
                    success: function(data) {
                        returnStr = data;
                    }
                });
            }
            return returnStr;
        };

        this.setSaveUrl = function(saveurl) {
            this.saveUrl = saveurl;
        };

        this.deleteEvent = function () {
            var grid = this;
            var returnStr;
            var deleteby = ps.UpdataModel.deleteby;
            if (!grid.hasSelected()) {
                $.JMessage("message1-" + ps.ele, "温馨提示:", "你没有选择行", "question");
            } else {
                var source = "{";
                var arr = grid.getSelectedRowIndexs();
                for (var i = 0; i < arr.length; i++) {
                    for (var a = 0; a < deleteby.length; a++) {
                        a == deleteby.length - 1 ? source = source + "\"" + deleteby[a] + "\":\"" + grid.data[arr[i]].getValue(deleteby[a]) + "\"" : source = source + "\"" + deleteby[a] + "\":\"" + grid.data[arr[i]].getValue(deleteby[a]) + "\",";
                    }
                    i == arr.length - 1 ? source = source + "}" : source = source + "},{";
                }
                var deleteUrl = "";
                var data = "deleteSource=[" + source + "]";

                $.JMessage("message2-" + ps.ele, "温馨提示:", "你真的要删除选中的行吗?", "YNC", function(val) {
                    $.ajax({
                        type: "post",
                        url: ps.UpdataModel.DelUrl,
                        complete:function() {
                            if (arr.length == grid.display) {
                                if (grid.page > 1 && grid.page == grid.pageCount) grid.page = grid.page - 1;
                                $('.input', fun.pDiv).val(grid.page);
                            }
                            grid.msgCount = grid.msgCount - arr.length;
                            grid.pageCount = Math.ceil((grid.msgCount / grid.pageSize));
                            $('.count', fun.pDiv).html(grid.pageCount);
                            fun.bind(grid.url, grid.ajaxdata, grid.page, false, grid);
                        },
                        data: data,
                        async:false,
                        success: function(msg) {
                            returnStr = msg;
                        }
                    });
                });
                return returnStr;
            }
        };

        this.addEvent = function(row) {
            var grid = this;
            if (this.data.length == ps.PagingToolbar.pageSize) this.data.pop();
            var map = new Map();
            $.each(row, function(i, n) {
                map.put(i, n);
            });
            this.data.unshift(map);
            fun.addData(this.data, false, true);
        };

        this.isSelect = function(tr) {
            if ($('td:first', tr).find('input').attr("checked") == true) {
                return true
            } else {
                return false
            }
        };

        this.getRowNo = function(ele) {
            return ele.attr('index');
        };

        this.getRow = function(index) {
            return this.data[parseInt(index)];
        };

        this.getSelectedByCols = function(nameArr){
            var grid = this;
            var arr = grid.getSelectedRowIndexs();
            for(var i=0;i<arr.length;i++){
                grid.getRow(arr[i]);
            }
        },

        this.getSelectedRowIndexs = function() {
            var grid = this;
            var i = 0;
            var indexArr = [];
            if (ps.selModel == 'CheckModel' || ps.selModel == 'TdSelectionModel') {                             //CheckModel,TdSelectionModel,RowSelectionModel
                $('tr', $(fun.bDiv)).each(function(index) {
                    if (grid.isSelect($(this))) {
                        var index = grid.getRowNo($(this));
                        indexArr[i] = index;
                        i++;
                    }
                });
                return indexArr;
            } else {
                $('tr', $(fun.bDiv)).each(function(index) {
                    if ($(this).hasClass('trSelected')) {
                        var index = grid.getRowNo($(this));
                        indexArr[i] = index;
                    }
                });
                return indexArr;
            }
        };

        this.getFristSelectRow = function() {
            return this.getRow(this.getSelectedRowIndexs()[0]);
        };

        this.getSelected = function() {

        };

        this.getTdBySelected = function() {
            var val = '';
            $('tr', $(fun.bDiv)).each(function(index) {
                var tr = $(this);
                if (grid.isSelect(tr)) {
                    $(this).find('td').each(function() {
                        if ($(this).hasClass('tdSelected')) {
                            val = grid.data[grid.getRowNo(tr)].getValue($(this).attr('name'));
                        }
                    })
                }
            });
            return val;
        };

        this.getNowPage = function() {
            return grid.page;
        };

        this.hasSelected = function() {
            if (this.getSelectedRowIndexs().length == 0) {
                return false;
            } else {
                return true;
            }
        };

        this.setRowHeight = function(rowHeight){
            this.rowHeight = rowHeight;
        };

        this.getEditorsTd = function() {
            return this.find("tr td[editor='true']", $(fun.bDiv));
        };
        this.getAllTdObj = function() {
            return this.getAllTrObj().find('td:gt(0)');
        };
        this.getAllTrObj = function() {
            return $('tr', $(fun.bDiv));
        };
        this.getTbarValue = function(ele) {
            return $('#' + ele, $(fun.tbDiv)).val();
        };

        this.disabled = function(ele) {
            typeof ele == 'string' ? $('#' + ele, this).unbind('click').attr("disabled", true).css({
                'color':'#F0F0F0'
            }) : ele.attr("disabled", true);
        };

        this.usabled = function(ele) {
            typeof ele == 'string' ? fun.buttonEvent(this.toolbarMap.getValue(ele), $('#' + ele, this).css({
                'color':'#444444'
            }).attr("disabled", false)) : ele.attr("disabled", false);
        };

        this.reload = function(url, data) {
            if (url) {
                this.url = url;
                this.ajaxdata = data;
                fun.bind(url, data, 1, true, this);
            } else {
                this.ajaxdata = data;
                fun.bind(this.url, data, this.page, false, this);
            }
        };

        fun.bodyDiv = document.createElement('div');
        fun.mDiv = document.createElement('div');
        fun.hDiv = document.createElement('div');
        fun.bDiv = document.createElement('div');
        fun.tDiv = document.createElement('div');
        fun.pDiv = document.createElement('div');
        fun.vGrip = document.createElement('div');
        fun.pDrag = document.createElement('div');
        fun.tbDiv = document.createElement('div');
        fun.lDiv = document.createElement('div');
        fun.mkDiv = document.createElement('div');

        this.initHtml = function() {
            var grid = this;
            this.width(ps.width).addClass('flexigrid');
            fun.createBody(this);
            fun.createTitle(this);
            fun.createToolbar(this);
            fun.createHr(this);
            fun.createGbody(this);
            if (grid.total) fun.createTotal(this);
            fun.createPager(this);
            if (ps.hasBotton)fun.createBotton(this);
            if (ps.dblUpdate) {
                fun.TrsDblclick(this)
            }
            fun.createLoader(this);

            $(".ptogtitle", $(fun.mDiv)).click(function() {
                if ($(this).attr('ishide') == 'false') {
                    $(fun.hDiv,fun.bDiv,fun.tbDiv,fun.vGrip,fun.pDiv,fun.tDiv).hide();
                    $(this).attr('ishide', 'true');
                } else {
                    $(fun.hDiv,fun.bDiv,fun.tbDiv,fun.vGrip,fun.pDiv,fun.tDiv).show();
                    $(this).attr('ishide', 'false');
                }
            })
        };

        this.init = function () {
            this.initHtml();
        };
        this.init();
        return this;
    };
})(jQuery);

 

 

    先写这么多,下一篇文章中我会对部分代码进行注释说明

你可能感兴趣的:(jquery,Ajax,css,chrome,IE)