欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

easyui-datagrid开发实践(总结)

程序员文章站 2022-11-25 08:47:30
一,引言 工作的需要,做了3年的wpf(mvvm)……,又因为项目的需求,回归到web的开发。 3 years ago,vue是我三年前没用过的玩意儿。...

一,引言

工作的需要,做了3年的wpf(mvvm)……,又因为项目的需求,回归到web的开发。

  • 3 years ago,vue是我三年前没用过的玩意儿。
  • 3 years ago,bootstrap组件没现在成熟。
  • 3 years ago,font awesome的普及度没有现在高。
  • 3 years ago,ui组件的选择也没有现在多。

easyui-datagrid开发实践(总结)

二,项目的前端(easyui模板订制)

整个项目采用了oracle  + dapper  + castle + mvc + easyui的技术结合,本篇博客重点介绍easyui。

easyui的默认风格看久了很容易产生视觉疲劳,在这个项目中,我个性化订制风格。

订制easyui模板的工作量是挺大的,我用了一个偷懒的方法,花了几百块钱在网上买了几个easyui的皮肤,然后对这些皮肤,进行优化和重构。

money比较紧的同学,可以去下载easyui的免费皮肤。

easyui-datagrid开发实践(总结)

三,easyui-datagrid的基本使用:

1,加载数据

a,通过post,url的方法向后端请求数据,如图所示:

easyui-datagrid开发实践(总结)

      $('#list').datagrid({
        title: "交易公司",
        loadmsg: '@commonresource.processing',
        toolbar: '#tb',
        width: "100%",
        height: "100%",
        //idfield:"id",
        //data: getdata(),
        url: "@url.action("getlist")",
        methord: 'post',
        rownumbers: true,
        autorowheight: false,
        fit: true,
        //fitcolumns: true,
        striped: true,   //奇偶行
        singleselect: true,//单选模式
        checkonselect: false,
        selectoncheck: false,
        collapsible: true,
        pagination: true,
        pagenumber: 1,
        pagesize: 10,
        pagelist: [10, 20],
        queryparams: { },
        columns: [[
          { field: 'company_name', title: '公司名称', width: 100, sortable: false },
          { field: 'abbreviation', title: '简称', width: 100, sortable: false },
          { field: 'business_address', title: '经营地址', width: 100, sortable: false },
          { field: 'registered_address', title: '注册地址', width: 100, sortable: false },
          { field: 'tel', title: '电话', width: 100, sortable: false },
          { field: 'fax', title: '传真', width: 100, sortable: false },
          { field: 'contactor', title: '联系人', width: 100, sortable: false },
          { field: 'payment', title: '结算方式', width: 100, sortable: false },
          { field: 'beneficiary_name', title: '开户名称', width: 100, sortable: false },
          { field: 'beneficiary_address', title: '开户地址', width: 100, sortable: false },
          { field: 'advising_bank', title: '通知行', width: 100, sortable: false },
          { field: 'bank_address', title: '银行地址', width: 100, sortable: false },
          { field: 'swift_code', title: '银行代码', width: 100, sortable: false },
          { field: 'beneficiary_account', title: '银行账户', width: 100, sortable: false },
          { field: 'company_chop', title: '电子章', width: 100, sortable: false },
          { field: 'send_url', title: '发件邮箱链接', width: 100, sortable: false },
          { field: 'send_email', title: '发件人邮箱', width: 100, sortable: false },
          { field: 'remark', title: '备注', width: 100, sortable: false },
          { field: 'created_by', title: '创建人', width: 100, sortable: false },
          { field: 'creation_date', title: '创建日期', width: 100, sortable: false },
          { field: 'modify_by', title: '修改人', width: 100, sortable: false },
          { field: 'modify_date', title: '修改日期', width: 100, sortable: false },
        ]],

      });
    });

b,先定义好了datagrid的属性以及列,再通过loaddata的方法设置datagrid的数据

$('#detail').datagrid({
  loadmsg: '@commonresource.processing',
  toolbar: '#tb',
  width: "100%",
  height: "100%",
  //data: [],
  rownumbers: true,
  autorowheight: false,
  fit: true,
  fitcolumns: true,
  striped: true,
  singleselect: true,
  collapsible: false,
  pagination: false,
  queryparams: { },
  columns: [[
    { field: 'country_name', title: '国家名称', width: 100, sortable: false },
    { field: 'item_number', title: '物料编码', width: 100, sortable: false },
  ]],
});

var returndata = json.parse(response.data);
$('#detail').datagrid("loaddata", returndata);

2,合并单元格

有时候用户需要如下图的效果

easyui-datagrid开发实践(总结)

可以在datagrid的onloadsuccess事件里增加如下代码:

onloadsuccess: function (data) {
  //var opts = $('#list').datagrid('getcolumnfields');
  var opts = new array("item_number", "country_name", "item_desc", "item_desc_en", "item_type", "unit", "hs_code", "destination_code", "status", "remark", "create_user", "create_date");
  var rowscount = data.rows.length;
  var mark = 1;
  for (var j = 1; j < rowscount; j++)
  {
    var precellval = data.rows[j - 1]["material_id"];
    var currentcellval = data.rows[j]["material_id"];
    if (precellval == currentcellval) {
      mark += 1;
      for (var c = 0; c < opts.length; c++) {
        var columnname = opts[c];
        $(this).datagrid('mergecells', {
          field: columnname,
          index: j + 1 - mark,
          rowspan: mark
        });
      }
    }
    else {
      mark = 1;
    }
  }
},

3,行,列变色

easyui-datagrid开发实践(总结)

针对这样的行,列变色效果:

a,行变色

easyui-datagrid开发实践(总结)

$('#detail').datagrid({
  loadmsg: '@commonresource.processing',
  toolbar: '#tb',
  width: "100%",
  height: "100%",
  url: "@url.action("getlines")",
  methord: 'post',
  rownumbers: true,
  autorowheight: false,
  fit: true,
  fitcolumns: true,
  striped: true,
  singleselect: true,
  collapsible: false,
  pagination: false,
  queryparams: { hid: $("#hid").val() },
  columns: [[
    { field: 'material_no', title: '物料号', width: 100, sortable: false },
    { field: 'description', title: '中文描述', width: 100, sortable: false },
    { field: 'en_description', title: '英文描述', width: 100, sortable: false },
    { field: 'unit', title: '单位', width: 100, sortable: false },
    { field: 'quantity', title: '工单数量', width: 100, sortable: false },
    { field: 'total_actual_send_quantity', title: '已出货数量', width: 100, sortable: false },
    { field: 'remark', title: '备注', width: 100, sortable: false },
  ]],
  rowstyler: function (index, row) {
    if (row.quantity == 0) {
      return 'background-color:pink;color:blue;font-weight:bold;';
    }
  },
});

b,列变色

easyui-datagrid开发实践(总结)

$('#detail').datagrid({
  loadmsg: '@commonresource.processing',
  width: "100%",
  height: "100%",
  data: [],
  rownumbers: true,
  autorowheight: false,
  fit: true,
  fitcolumns: true,
  striped: true,
  singleselect: true,
  checkonselect: false,
  selectoncheck: false,
  collapsible: false,
  pagination: false,
  queryparams: {},
  columns: [[
    { field: 'sel', checkbox: true },
    { field: 'material_no', title: '物料号', width: 80, sortable: false },
    { field: 'description', title: '中文描述', width: 80, sortable: false },
    { field: 'unit', title: '单位', width: 80, sortable: false },
    { field: 'quantity', title: '工单数量', width: 80, sortable: false },
    { field: 'total_actual_send_quantity', title: '已出货数量', width: 80, sortable: false },
    { field: 'remain_quantity', title: '剩余数量', width: 80, sortable: false },
    {
      field: 'actual_send_quantity', title: '本次出货', width: 80, sortable: false,
      editor: { type: 'numberbox', options: { required: true, min: 0 }, },
      styler: function (value, row, index) {
        return 'background-color:#ecffff;';
      },
    },
    {
      field: 'remark', title: '备注', width: 80, sortable: false,
      editor: { type: 'textbox', options: { validtype: 'length[1,20]' }, },
      styler: function (value, row, index) {
        return 'background-color:#ecffff;';
      },
    },
  ]],

4,为datagrid添加工具条

如下效果的工具条,是通过datagrid的 toolbar 属性来指定,要留意的是toolbar的控件名称需要加上#符号。

easyui-datagrid开发实践(总结)

html代码:

<div id="tb">
  <a id='condition' href='#' class='btn btn-default more'><i class='fa fa-ellipsis-v'></i>  查询条件</a>
  @html.toolbutton(string.format(@"<a id='btncreate' href='#' class='btn btn-default'><i class='fa fa-plus'></i>  {0}</a>", @commonresource.add), actioncode.create)
  @html.toolbutton(string.format(@"<a id='btnedit' href='#' class='btn btn-default'><i class='fa fa-pencil'></i>  {0}</a>", @commonresource.edit), actioncode.edit)
  @html.toolbutton(string.format(@"<a id='btndelete' data-content='delete 1' href='#' class='btn btn-primary'><i class='fa fa-trash'></i>  {0}</a>", @commonresource.delete), actioncode.delete)
</div>

js代码:

easyui-datagrid开发实践(总结) 

5,做增,删,改操作

a,为datagrid增加一行

function addcallback(data) {
  $('#list').datagrid('insertrow', {
    index: 0,
    row: data,
  });
  layer.msg('@commonresource.addsuccess', { icon: 1, time: 1000 });
}

b,为datagrid编辑一行

function editcallback(data) {
  var selectdata = $('#list').datagrid('getselected');
  var selectindex = $('#list').datagrid('getrowindex', selectdata);
  $('#list').datagrid('updaterow', {
    index: selectindex,
    row: data,
  });
  layer.msg('@commonresource.modifysuccess', { icon: 1, time: 1000 });
}

c,为datagrid删除一行

$("#btnlinedelete").click(function () {
  var row = $('#detail').treegrid('getselected');
  if (row != null) {
    var rowindex = $('#detail').datagrid('getrowindex', row);
    $('#detail').datagrid('deleterow', rowindex);
    layer.msg('@commonresource.deletesuccess', { icon: 1, time: 1000 });
  }
  else {
    layer.msg('@commonresource.noselectedrecord', { icon: 2, time: 1000 });
  }
});

d,treegrid的操作方法略有区别,附上源码:

  function addcallback(data) {
    var row = $('#list').treegrid('getselected');
    $('#list').treegrid('append', {
      parent: data.parent_id,
      data: [{
        id: data.id,
        name: data.name,
        en_name:data.en_name,
        code: data.code,
        enable: data.enable,
        sort: data.sort,
      }]
    });
    layer.msg('@commonresource.addsuccess', { icon: 1, time: 1000 });
  }

  function editcallback(data) {
    var row = $('#list').treegrid('getselected');
    $('#list').treegrid('update', {
      id: row.id,
      row: {
        name: data.name,
        en_name: data.en_name,
        code: data.code,
        enable: data.enable,
        sort: data.sort,
      }
    });
    layer.msg('@commonresource.modifysuccess', { icon: 1, time: 1000 });
  }

  $("#btndelete").click(function () {
    var row = $('#list').treegrid('getselected');
    if (row != null) {
      layer.confirm('@commonresource.confirmdelete', {
        btn: ['@commonresource.sure', '@commonresource.cancel'],
        shadeclose: true,
      }, function () {
        if (row.childcount == 0 || typeof (row.childcount) == 'undefined') {
          $.post("@url.action("delete")/" + row.id, function (data) {
            if (data == "1") {

              $("#list").treegrid('remove', row.id);
              layer.msg('@commonresource.deletesuccess', { icon: 1, time: 1000 });
            }
            else {
              layer.msg('@commonresource.deletefailed', { icon: 2, time: 1000 });
            }

          }, "json");
        }
        else {
          layer.msg('@commonresource.noselectedrecord', { icon: 2, time: 1000 });
        }

      }, function () {
      });
    }
    else {
      layer.msg('@commonresource.noselectedrecord', { icon: 2, time: 1000 });
    }
  });

6,编辑单元格

easyui-datagrid开发实践(总结) 

具体代码实现

    var taxtypelist = json.parse($("#taxtypelist").val());
    var manufacturelist = json.parse($("#manufacturelist").val());

    $.extend($.fn.datagrid.methods, {
      editcell: function (jq, param) {
        return jq.each(function () {
          var opts = $(this).datagrid('options');
          var fields = $(this).datagrid('getcolumnfields', true).concat($(this).datagrid('getcolumnfields'));
          for (var i = 0; i < fields.length; i++) {
            var col = $(this).datagrid('getcolumnoption', fields[i]);
            col.editor1 = col.editor;
            if (fields[i] != param.field) {
              col.editor = null;
            }
          }
          $(this).datagrid('beginedit', param.index);
          for (var i = 0; i < fields.length; i++) {
            var col = $(this).datagrid('getcolumnoption', fields[i]);
            col.editor = col.editor1;
          }
        });
      }
    });

    var editindex = -1;
    function endeditcal() {
      if (editindex == -1) {
        return true;
      }
      if ($('#detail').datagrid('validaterow', editindex)) {
        $('#detail').datagrid('endedit', editindex);
        editindex = -1;
        return true;
      }
      else {
        return false;
      }
    }

    $('#detail').datagrid({
      loadmsg: '@commonresource.processing',
      toolbar: '#tb',
      width: "100%",
      height: "100%",
      data: json.parse($("#materialdetailliststr").val()),
      rownumbers: true,
      autorowheight: false,
      fit: true,
      fitcolumns: true,
      striped: true,
      singleselect: true,
      collapsible: false,
      pagination: false,
      queryparams: { },
      columns: [[
        {
          field: 'material_use', title: '用途', width: 100, sortable: false,
          formatter: function (value) {
            for (var i = 0; i < manufacturelist.length; i++) {
              if (manufacturelist[i].key == value) return manufacturelist[i].value;
            }
            return value;
          },
          editor: {
            type: 'combobox',
            options: {
              valuefield: 'key',
              textfield: 'value',
              data: manufacturelist,
              required: true,
              panelheight: "auto",
              editable:false,
            }
          },
        },

        {
          field: 'tax_type', title: '税别', width: 100, sortable: false,
          formatter: function (value) {
            for (var i = 0; i < taxtypelist.length; i++) {
              if (taxtypelist[i].key == value) return taxtypelist[i].value;
            }
            return value;
          },
          editor: {
            type: 'combobox',
            options: {
              valuefield: 'key',
              textfield: 'value',
              data: taxtypelist,
              required: true,
              panelheight: "auto",
              editable: false,
            }
          },
        },
        { field: 'tax_bcd', title: 'bcd', width: 100, sortable: false, editor: { type: 'numberbox', options: { required: true, suffix: '%', precision: 2, min: 0, max: 100, } } },
        { field: 'tax_cess', title: 'cess', width: 100, sortable: false, editor: { type: 'numberbox', options: { required: true, suffix: '%', precision: 2, min: 0, max: 100, } } },
        { field: 'tax_igst', title: 'igst', width: 100, sortable: false, editor: { type: 'numberbox', options: { required: true, suffix: '%', precision: 2, min: 0, max: 100, } } },
      ]],
      @if (request.params["operate"] != "view")
        {
          <text>
          onclickcell: function (index, field, value) {
            if (endeditcal()) {
              $(this).datagrid('selectrow', index).datagrid('editcell', { index: index, field: field }); //编辑一个单元格
              //$(this).datagrid('beginedit', index); //编辑一行
              editindex = index;
            }
            else {
              layer.msg('当前行的数据编辑有误', { icon: 2, time: 1000 });
            }
          },
          onafteredit: function (index, row, changes) {
            var rowdata = $(this).datagrid('getdata').rows[index];
            $('#detail').datagrid('updaterow', {
              index: index,
              row: {},
            });
          },
          onloadsuccess: function (data) {
            for (var index = 0; index < data.rows.length; index++) {
              $(this).datagrid('beginedit', index);
            }
          },
          </text>
        }
    });

    $("#btnlinecreate").click(function () {

      if (endeditcal()) {
        editindex = 0;
        $('#detail').datagrid('insertrow', {
          index: editindex,
          row: {},
        });
        $('#detail').datagrid('selectrow', editindex);
        $('#detail').datagrid('beginedit', editindex);
      }
      else {
        layer.msg('当前行的数据编辑有误', { icon: 2, time: 1000 });
      }
    });

    $("#btnlinedelete").click(function () {
      var row = $('#detail').treegrid('getselected');
      if (row != null) {
        var rowindex = $('#detail').datagrid('getrowindex', row);
        $('#detail').datagrid('deleterow', rowindex);
        layer.msg('@commonresource.deletesuccess', { icon: 1, time: 1000 });
      }
      else {
        layer.msg('@commonresource.noselectedrecord', { icon: 2, time: 1000 });
      }
    });

    $("#btnsave").click(function () {
      var summaryvalidate = true;
      var rows = $("#detail").datagrid("getrows");
      $(rows).each(function (index, itemdata) {
        if ($('#detail').datagrid('validaterow', index)) {
          $('#detail').datagrid('endedit', index);
        }
        else {
          summaryvalidate = false;
          return false;
        }
      });
      if (summaryvalidate) {
        if (rows.length == 2) {
          $("#materialdetailliststr").val(json.stringify(rows));
        }
        else {
          layer.msg('税别,用途应该设置为2行数据', { icon: 2, time: 1000 });
          return false;
        }
      }
      else {
        layer.msg('当前表单数据编辑有误', { icon: 2, time: 1000 });
        return false;
      }

      var check = $('form').form('validate');
      if (check) {
        $.ajax({
          url: "@url.action("creatematerial")",
          type: "post",
          data: $("form").serialize(),
          datatype: "json",
          success: function (data) {
            if (data.key == "1") {
              parent.$("#list").datagrid('reload');
              var index = parent.layer.getframeindex(window.name);
              parent.layer.close(index);
              parent.layer.msg('@commonresource.addsuccess', { icon: 1, time: 1000 });
            }
            else {
              layer.msg("物料编号'" + data.value.item_number + "'在数据库中已添加", { icon: 2, time: 1000 });
            }
          },
          error: function (jqxhr, textstatus, errorthrown) {
            layer.msg('@commonresource.addfailed', { icon: 2, time: 1000 });
          }
        });
      }
    });

7,重置datagrid布局  $('#list').datagrid("resize");

$(function () {
  $(".more").click(function () {
    $(this).closest(".conditions").siblings().toggleclass("hide");
    $('#list').datagrid("resize");
  });
})

四,总结

这些技巧,在帮助文档里也说的很详细,我只是把这些技术用于实践。希望对大家的学习有所帮助,也希望大家多多支持。