自写Jquery插件 Datagrid

时间:2022-03-16 09:50:39

原创文章,转载请注明出处,谢谢!https://www.cnblogs.com/GaoAnLee/p/9086582.html 

废话不多说,先上个整体效果:

自写Jquery插件 Datagrid

html

<div id='datagrid'></div>
<div id='barcon'></div>

css

@CHARSET "UTF-8";
div {
    overflow: hidden;
}

ul, li {
    list-style: none;
    display: inline-block;
}

#table, #table .table-th, #table .table-td {
    border: 0.5px solid #D5D5D5;
    text-align: center;
}

#table .caption {
    display: table-caption;
    text-align: left;
    font-size: 18px;
    font-weight: bold;
    height: 50px;
    line-height: 50px;
}

#datagrid, .main-datagrid {
    width: 100%;
    height: 100%;
    font-size: 13px;
}

#table {
    display: table;
}

#table .table-tr {
    display: table-row;
}

#table .table-th, #table .table-td {
    display: table-cell;
}

#table .table-th {
    background-color: #EBEBEB;
    height: 30px;
    line-height: 30px;
    color: #000000;
    font-weight: bold;
}

#table .table-td {
    height: 40px;
    line-height: 40px;
}

#table .table-tr:nth-child(even) {
    background-color: #F8F8F8;
}

#table .table-tr:nth-child(n+2):hover {
    background-color: #EAF4F8;
}

input[type='checkbox'],#barcon span a, #barcon span i{
    cursor: pointer;
}

#barcon {
    font-size: 15px;
}

#barcon span {
    height: 50px;
    line-height: 50px;
}

#barcon span:nth-child(1) {
    float: left;
}

#barcon span:nth-child(2) {
    float: right;
    margin-right: 20px;
}

#barcon span a {
    background-color: #ffffff;
    color: #000000;
    margin: 0 3px;
    padding: 2px 2px;
    font-size: 12px;
}

#barcon span input {
    height: 20px;
    width: 30px;
    border: 1px solid #AAAAAA;
}

#barcon span a, #barcon span em, #barcon span i, #barcon span input {
    margin: 0 5px;
}

#barcon span a:hover, #barcon span i:hover, #barcon span em:hover {
    color: #3c8dbc;
}

jquery.datagrid.js

/*
* datagrid
* auther:GaoAnLee
* <div id='datagrid'>
*   //js-data
* </div>
* <div id='barcon'>
*   //js-data
* </div>
*/
;
(function($, window, document, undefined) {
    //初始化
    function _init(datagrid, b) {
        var _this = datagrid.element;
        var options = $.data(_this, 'datagrid').options;
        var len = options.columns.length
        if (b) {
            var buffer = '';
            buffer += '<div class=\"main-datagrid\">';
            buffer += '<div id=\"table\">';
            if (options.showHeader) {
                buffer += '<div class=\"caption\">' + options.headerText + '</div>';
            }
            var hasCheckBox = options.showCheckBox;
            buffer += '<div class=\"table-tr\">';
            if (hasCheckBox) {
                buffer += '<div class=\"table-th checkbox\"><input type=\"checkbox\" /></div>';
            }
            for (var i = 0; i < len; i++) {
                buffer += '<div class=\"table-th\">' + options.columns[i].label + '</div>';
            }
            buffer += '</div></div></div>';
            _this.append(buffer);
        }
        $(options.datagrid + ' ' + options.table + ' ' + options.th).width(options.tdWidth);
        $(options.checkbox).width(27);
        //动作
        actions(options);
        //效果
        effect(options);
    }
    //通过ajax加载数据
    function loadDataByAjax(options) {
        $.ajax({
            type: options.ajaxType,
            url: options.loadUrl,
            dataType: options.dataType,
            async: false,
            success: function(data) {
                var datagrid = eval('(' + data + ')');
                warpDatagrid(datagrid, options);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == 'error') {
                    console.log('ajax error ! value of textStatus is error ! datagrid.js:line 54');
                }
            }
        });
    }

    function warpDatagrid(datagrid, options) {
        if (datagrid.code == 200) {
            var buffer = '';
            var len = datagrid.data.length;
            var lenColumns = options.columns.length;
            for (var i = 0; i < len; i++) {
                buffer += '<div class=\"table-tr\">';
                if (options.showCheckBox) buffer += '<div class=\"table-td checkbox\"><input type=\"checkbox\" /></div>';
                for (var j = 0; j < lenColumns; j++) {
                    var column = options.columns[j].name;
                    var type = options.columns[j].type;
                    var value = datagrid.data[i][column];
                    buffer += '<div class=\"table-td\">'
                    if (type == 'string') buffer += value;
                    if (type == 'timeStamp') {
                        value = timestampToTime(parseInt(value));
                        buffer += value;
                    }
                    if (type == 'boolean') {
                        var no = options.columns[j].value.no;
                        var yes = options.columns[j].value.yes;
                        value = parseInt(value);
                        value = value == 0 ? no : yes;
                        buffer += value;
                    }
                    buffer += '</div>'
                }
                buffer += '</div>';
            }
            $(options.table).append(buffer);
        } else {
            console.log('后台获取数据失败!错误信息:' + datagrid.message);
        }
    }
    //翻页
    function paging(options) {
        var totalNumber = $(options.table).children().length - 2;
        var page = options.page;
        var pageSize = options.pageSize;
        var pageNumber = parseInt((totalNumber - 2) / pageSize) + 1;
        var startRow = (page - 1) * pageSize + 2; //2 12 22 32
        var endRow = page * pageSize + 1; //11 21 31 41
        var total = totalNumber + 1;
        var endRow = endRow > total ? total : endRow;
        var row = $(options.table).children().eq(0);
        for (var i = 2; i < totalNumber + 2; i++) {
            row = $(options.table).children().eq(i);
            if (i >= startRow && i <= endRow) {
                row.show();
            } else {
                row.hide();
            }
        }
        var buffer = '';
        buffer += '<span>共<em class=\"total-number\">' + totalNumber + '</em>条数据</em>,每页';
        if (pageSize == 10) {
            buffer += '<select class=\"pageSize\"><option value=\"10\" selected >10条</option><option value=\"20\">20条</option><option value=\"50\">50条</option></select>';
        } else if (pageSize == 20) {
            buffer += '<select class=\"pageSize\"><option value=\"10\">10条</option><option value=\"20\" selected >20条</option><option value=\"50\">50条</option></select>';
        } else if (pageSize == 50) {
            buffer += '<select class=\"pageSize\"><option value=\"10\">10条</option><option value=\"20\">20条</option><option value=\"50\" selected>50条</option></select>';
        }
        buffer += '</span><span>';
        buffer += '<a class=\"frist-page\">首页</a><i class=\"left fa fa-caret-left\"></i><em class=\"now-page\">' + page + '</em>/<em class=\"total-page\">' + pageNumber + '</em><i class=\"right fa fa-caret-right\"></i><a class=\"last-page\">尾页</a>转到<input type=\"txt\" />页</span>';
        $(options.barcon).html(buffer);
    }
    //pageSize选择  翻页 跳页等action
    function actions(options) {
        $(options.barcon).on('change', '.pageSize', function() {
            var value = parseInt($(this).find('option:selected').val());
            var page = parseInt($('.now-page').html());
            $(options.datagrid).myDatagrid('page', {
                page: page,
                pageSize: value
            });
            options.pageSize = value;
        });
        $(options.barcon).on('click', '.left', function() {
            var page = parseInt($('.now-page').html());
            var pageSize = options.pageSize;
            if (page > 1) {
                $(options.datagrid).myDatagrid('page', {
                    page: page - 1, //要去往的页码
                    pageSize: pageSize
                });
            }
        });
        $(options.barcon).on('click', '.right', function() {
            var page = parseInt($('.now-page').html());
            var pageSize = options.pageSize;
            var totalNumber = $(options.table).children().length - 2;
            var pageNumber = parseInt(totalNumber / pageSize) + 1;
            if (page < pageNumber) {
                $(options.datagrid).myDatagrid('page', {
                    page: page + 1, //要去往的页码
                    pageSize: pageSize
                });
            }
        });
        $(options.barcon).on('keydown', 'input', function(event) {
            if (event.keyCode == '13') {
                var value = parseInt($(this).val());
                var pageSize = options.pageSize;
                var totalNumber = $(options.table).children().length - 2;
                var pageNumber = parseInt(totalNumber / pageSize) + 1;
                if (value >= 1 && value <= pageNumber) {
                    $(options.datagrid).myDatagrid('page', {
                        page: value, //要去往的页码
                        pageSize: pageSize
                    });
                } else {
                    alert('输入的页码不对!不在可选页码范围内!');
                }
            }
        });
        $(options.barcon).on('click', '.frist-page', function() {
            var pageSize = options.pageSize;
            $(options.datagrid).myDatagrid('page', {
                page: 1, //要去往的页码
                pageSize: pageSize
            });
        });
        $(options.barcon).on('click', '.last-page', function() {
            var pageSize = options.pageSize;
            var totalNumber = $(options.table).children().length - 2;
            var pageNumber = parseInt(totalNumber / pageSize) + 1;
            $(options.datagrid).myDatagrid('page', {
                page: pageNumber, //要去往的页码
                pageSize: pageSize
            });
        });
    }
    //datagrid 效果  选择单行,checkbox选中,全选,反选
    function effect(options) {
        $(options.table).on('click', options.tr, function(event) {
            var index = $(this).index();
            var page = options.page;
            var pageSize = options.pageSize;
            var totalNumber = $(options.table).children().length - 2;
            var startRow = (page - 1) * pageSize + 2; //2 12 22 32
            var endRow = page * pageSize + 1; //11 21 31 41
            var total = totalNumber + 1;
            var endRow = endRow > total ? total : endRow;
            var e = event.srcElement ? event.srcElement : event.target;
            var checkbox = $(this).children().eq(0).children('input');
            if (e != '[object HTMLInputElement]') {
                if (checkbox.prop('checked')) {
                    checkbox.prop('checked', false);
                    $(options.table).children(options.tr).eq(0).find('input').prop('checked', false);
                } else {
                    checkbox.prop('checked', true);
                    var flag = true;
                    for (var i = startRow; i <= endRow; i++) {
                      var checkboxTamp = $(options.table).children().eq(i).children().eq(0).children('input');
                      var f = checkboxTamp.prop('checked');
                      if(!f){
                        flag = false;
                      }
                    }
                    if(flag){
                      $(options.table).children(options.tr).eq(0).find('input').prop('checked', true);
                    }
                }
            }
            if (index == 1) {
                firstCheckboxHasChecked(checkbox, options, startRow, endRow);
            }
        });
        $(options.table).children(options.tr).eq(0).find('input').on('change', function() {
            var page = options.page;
            var pageSize = options.pageSize;
            var totalNumber = $(options.table).children().length - 2;
            var startRow = (page - 1) * pageSize + 2; //2 12 22 32
            var endRow = page * pageSize + 1; //11 21 31 41
            var total = totalNumber + 1;
            var endRow = endRow > total ? total : endRow;
            firstCheckboxHasChecked($(this), options, startRow, endRow);
        });
    }
    function firstCheckboxHasChecked(checkbox, options, startRow, endRow) {
        if (checkbox.prop('checked')) {
            for (var i = startRow; i <= endRow; i++) {
                var checkboxTamp = $(options.table).children().eq(i).children().eq(0).children('input');
                checkboxTamp.prop('checked', true);
            }
        } else {
            for (var i = startRow; i <= endRow; i++) {
                var checkboxTamp = $(options.table).children().eq(i).children().eq(0).children('input');
                checkboxTamp.prop('checked', false);
            }
        }
    }
    var Datagrid = function(e, options) {
        this.element = e,
            this.defaluts = {
                datagrid: '#datagrid',
                table: '#table',
                checkbox: '.checkbox',
                tr: '.table-tr',
                th: '.table-th',
                td: '.table-td',
                barcon: '#barcon',
                headerText: '查询结果',
                showPaging: true, //默认显示分页
                pageSize: 10, //默认每页展示的数据数量
                showHeader: true, //默认显示表标题
                showCheckBox: true, //默认显示checkbox
                tdWidth: 100, //默认th宽度
                page: 1 //当前页码
            },
            this.options = $.extend({}, this.defaluts, options);
    };

    Datagrid.prototype = {
        //加载数据
        loadData: function(options) {
            if (options.loadType == 'ajax') {
                loadDataByAjax(options);
                paging(options);
            }
            return false;
        },
        //调页
        page: function(options) {
            paging(options);
            return false;
        }
    };

    $.fn.myDatagrid = function(target, parm) {
        var datagrid = new Datagrid(this, target);
        var options = {};
        if (typeof target == 'string' && typeof parm == 'string') {
            return datagrid[target](parm);
        }
        if (typeof target == 'string' && typeof parm == 'object') {
            options = $.extend({}, datagrid.defaluts, parm);
            return datagrid[target](options);
        }
        var state = $.data(this, 'datagrid');
        if (state) {
            options = $.extend({}, state.options, target);
        } else {
            options = $.extend({}, datagrid.defaluts, target);
        }
        $.data(this, 'datagrid', {
            options: options
        });
        this.each(function() {
            _init(datagrid, true);
        });
    };
})(jQuery, window, document);


$(function() {
    var columns = [{
        label: '用户编号',
        name: 'userID',
        type: 'string',
    }, {
        label: '用户名称',
        name: 'userName',
        type: 'string',
    }, {
        label: '手机号码',
        name: 'phoneNumber',
        type: 'string',
    }, {
        label: '用户密码',
        name: 'password',
        type: 'string',
    }, {
        label: '组织',
        name: 'organization',
        type: 'string',
    }, {
        label: '注册日期',
        name: 'createTime',
        type: 'timeStamp',
    }, {
        label: '最后登录日期',
        name: 'lastLoginTime',
        type: 'timeStamp',
    }, {
        label: '账号状态',
        name: 'status',
        type: 'boolean',
        value: {
            'no': '禁用',
            'yes': '启用'
        }
    }, {
        label: '登录状态',
        name: 'isOnline',
        type: 'boolean',
        value: {
            'no': '离线',
            'yes': '在线'
        }
    }];

    //默认必须参数为 columns
    var gridOptions = {
        columns: columns, //表头  必须
        headerText: '用户数据查询结果', //有默认值  查询结果
        tdWidth: ($('#datagrid').width() - 20 - 27) / columns.length, //设置单元宽度  有默认值 100
    };

    $('#datagrid').myDatagrid(gridOptions); //加载datagrid

    $('#datagrid').myDatagrid('loadData', {
        columns: columns, //表头  必须
        loadType: 'ajax', //加载数据的方式  必须
        ajaxType: 'get', //ajax type
        dataType: 'text', //ajax dataType
        loadUrl: 'data/datagrid.txt', //ajax url
    });
});