jquery easyui DataGrid简单示例


Posted in Javascript onJanuary 23, 2017

一、简单示例

HTML

<table id="tbList" striped="true" rownumbers="true" fix="true" fitcolumns="true" title="标题"
    idfield="ID" checkbox="true" url="@Url.Action("ListData")">
  <thead>
    <tr>
      <th field="ID" checkbox="true" width="30">
      </th>
      <th field="Name" width="200" align="center">
        名称
      </th> 
    </tr>
  </thead>
</table>

JS

$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {//查询方法
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});

二、基本用法

冻结列

$('#tbList').datagrid({ pagination: true,
      frozenColumns: [[
      { field: 'BId',checkbox:'true',width:30},
      { field: 'BNo', title: '牌号', width: 100 },
      { field: 'FNo', title: '班号', width: 100 }
    ]], 



 fitColumns:false //禁止自适应宽度、可以水平滚动
    });

去掉分页

$('#tbList').datagrid({pagination: true});

更改为

$('#tbList').datagrid();

$('#tbList').datagrid({pagination: false});

注意:同时需要设置table的高度,而且不能为auto

复选框以及单选

<table id="tbList" style="height: 330px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit" 
checkbox="true" idfield="Id" url="@Url.Action("ListData")">
<thead>
    <tr>
   <th field="Id" checkbox="true" width="150">
    
</th>


</tr>
</thead>
</table>

变为单选(添加singleSelect="true"  )

<table id="tbList" style="height: 330px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit" singleSelect="true" checkbox="true"  idfield="Id" url="@Url.Action("ListData")">

加载数据后默认全选:

$(document).ready(function () {
    $('#tbList').datagrid({ 
      onLoadSuccess: function (data) {
        $('#tbList').datagrid('selectAll');
      } 
    });

获取行数

$('#tbList').datagrid("getRows").length;

隐藏列

<th field="Dept" width="100" hidden="true">名称</th>

清空原有数据

方法1:

var item = $('#filegrid').datagrid('getRows');
      if (item) {
        for (var i = item.length - 1; i >= 0; i--) {
          var index = $('#filegrid').datagrid('getRowIndex', item[i]);
          $('#filegrid').datagrid('deleteRow', index);
        }
      }

方法2:(测试过)

$('#filegrid').datagrid('loadData', { total: 0, rows: [] });

解析:loadData:载入本地数据,旧记录将被移除。

行点击事件

$('#tbList').datagrid({ onClickRow: function () {//代码 } });

datagrip单击行的时候,将单选按钮设置为选中

<script type="text/javascript">
  var List = {};
  List.RadioFormatter = function (value, rec, index) {
    return "<input id='radio_id' name='radio_name' type='radio' value='" + rec.Id + "'/>";
  };

 $(document).ready( function(){ //呈现列表数据
$('#tbList').datagrid({ onClickRow:
      function () {
        //单击行的时候,将单选按钮设置为选中
        var id = $('#tbList').datagrid("getSelected");
        $("input[name='name']").each(function () {
          if ($(this).val() == id.Id) {
            $(this).attr("checked", true);
          }
        });
      }
    });
});
</script>
<table id="tbList" style="height: 300px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit"
     singleSelect="true" checkbox="true" idfield="Id" url="@Url.Action("ListData")">
      <thead>
        <tr>
          <th field="Id" width="30" formatter="PickupList.RadioFormatter">
          </th>
        </tr>
      </thead>
    </table>

 table中td的时间格式问题

1.页面

<th field="Test" formatter="Common.TimeFormatter" width="50" ></th>

2.js 

var Common = {
  //EasyUI用DataGrid用日期格式化
  TimeFormatter: function (value, rec, index) {
    if (value == undefined) {
      return "";
    }
    /*json格式时间转js时间格式*/
    value = value.substr(1, value.length - 2);
    var obj = eval('(' + "{Date: new " + value + "}" + ')');
    var dateValue = obj["Date"];
    if (dateValue.getFullYear() < 1900) {
      return "";
    }
    var val = dateValue.format("yyyy-mm-dd HH:MM");//控制格式
    return val.substr(11, 5);
  }

};

table中td内容太长自动换行

添加属性 nowrap="false"

将nowrap: false这个属性设置在table的属性中,不要设置在字段的属性中,字段可以设置宽度,这样就可以做到当文字长度超过规定的宽度后自动换行了

行和复选框的分离

方法一:(1.3版本才能用)

checkOnSelect="false" selectOnCheck="false"

注意:当使用$("#tbList").datagrid("getSelections");时候,只有行被选中,才能取到该行。一般情况,选中行时候,行为黄色背景。

eg.<table checkOnSelect="false"> </table> 

var selected = $("#tbList").datagrid("getSelections");
    if (selected.length == 0) {
      alert("请选择!");
      return;
    }

    var idString = "";
    $.each(selected, function (index, item) {
      idString += item.Id + ",";
    });

方法二(1.3版本之前的解决方法) 

var IsCheckFlag = true;
    $('#tbList').datagrid({
      pagination: true,
      onClickCell: function (rowIndex, field, value) {
        IsCheckFlag = false;
      },
      onSelect: function (rowIndex, rowData) {
        if (!IsCheckFlag) {
          IsCheckFlag = true;
          $("#tbList").datagrid("unselectRow", rowIndex);
        }
      },
      onUnselect: function (rowIndex, rowData) {
        if (!IsCheckFlag) {
          IsCheckFlag = true;
          $("#tbList").datagrid("selectRow", rowIndex);
        }
      }
    });

设置数据列表的样式

$(document).ready(function () {
    //呈现列表数据
    $('#tbList').datagrid({ pagination: true,
      rowStyler: function(index,row){
          if (row.ID< 10) {//那么数据的id字段小于10的,将显示为灰色字体
            return 'color:#999;';//和一般的样式写法一样
          }
        }
      });
  });

条件查询

复选框的bug:使用参数查询时候,在查询之前选中的选项 ,在查询之后,使用getSelections方法去获取,依旧存在该选项

解决方案:通过unselectAll在查询之前清空复选框即可

$("#btnSearch").click(function () {
      $('#tbList').datagrid("unselectAll");
      $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val() } });
    });

查询bug:使用参数查询时候,在查询之后,显示的当前页码还是之前的 ,不会重置为1,还是之前页码;如果当前总页数为比当前小,导致页面显示为空。比如,当前第三页,加入时间查询后,只有1页数据,那么当前页码还是3,导致页面显示空白。

解决方案:设置pageNumber为 1

$("#btnSearch").click(function () {
      $('#tbList').datagrid("unselectAll");
      $('#tbList').datagrid({ pageNumber: 1,queryParams: { SearchName: $("#SearchName").val() } });
    });

 三、行数据的增删改

HTML(不分页列表)

<table id="tbProductList" style="height: 500px; max-height: 500px;" fix="true" fitcolumns="true" idfield="ID" url="@Url.Action("ListData")"></table>

JS

$(document).ready(function () { 
    var datagrid;
    var editRow = undefined;
    datagrid = $("#tbList").datagrid({
      border: true,
      checkbox: true,
      iconCls: 'icon-save', //图标
      nowap: true, //列内容多时自动折至第二行
      pagination: false,
      rownumbers: true,
      striped: true, //行背景交换
      columns: [[//显示的列
       { field: 'ID', title: '编号', width: 100, align: 'center', sortable: true, checkbox: true },
       { field: 'Name', title: '名称', width: 100, sortable: true },
       {
         field: 'PriceType', title: '类型', width: 100, align: 'center',
         formatter: function (value, row) { return row.TypeName; },
         editor: {
           type: 'combobox', options: {
             valueField: 'Value',
             textField: 'Text',
             method: 'get',
             url: $("#TypeUrl").val(),
             required: true
           }
         }
       },
        {
          field: 'Price', title: '价格', width: 100, align: 'center',
          editor: {
            type: 'numberbox', options: {
              required: true,
              min: 0,
              precision: 2
            }
          }
        },
        {
          field: 'Count', title: '数量', width: 100, align: 'center',
          editor: {
            type: 'numberbox', options: {
              required: true,
              min: 0,
              precision: 0
            }
          }
        }
      ]],
      queryParams: { action: 'query' }, //查询参数
      toolbar: [{ text: '添加', iconCls: 'icon-add', handler: function () {//添加列表的操作按钮添加,修改,删除等
          //添加时先判断是否有开启编辑的行,如果有则把开户编辑的那行结束编辑
          if (editRow != undefined) {
            datagrid.datagrid("endEdit", editRow);
          }
          //添加时如果没有正在编辑的行,则在datagrid的第一行插入一行
          if (editRow == undefined) {
            datagrid.datagrid("insertRow", {
              index: 0, // index start with 0
              row: {

              }
            });
            //将新插入的那一行开户编辑状态
            datagrid.datagrid("beginEdit", 0);
            //给当前编辑的行赋值
            editRow = 0;
          }

        }
        }, '-',
       {
         text: '删除', iconCls: 'icon-remove', handler: function () {
           //删除时先获取选择行
           var rows = datagrid.datagrid("getSelections");
           //选择要删除的行
           if (rows.length > 0) {
             $.messager.confirm("提示", "你确定要删除吗?", function (r) {
               if (r) {
                 var ids = [];
                 for (var i = 0; i < rows.length; i++) {
                   ids.push(rows[i].ID);
                 } 
                 //将选择到的行存入数组并用,分隔转换成字符串
                 if ($.trim(ids) != "") {
                  //---- Delete(ids.join(','));//这是post
                 } else {
                   alert("请选择要删除的信息!");
                 }
               }
             });
           }
           else {
             $.messager.alert("提示", "请选择要删除的行", "error");
           }
         }
       }, '-',
       {
         text: '修改', iconCls: 'icon-edit', handler: function () {
           //修改时要获取选择到的行
           var rows = datagrid.datagrid("getSelections");
           //如果只选择了一行则可以进行修改,否则不操作
           if (rows.length == 1) {
             //修改之前先关闭已经开启的编辑行,当调用endEdit该方法时会触发onAfterEdit事件
             if (editRow != undefined) {
               datagrid.datagrid("endEdit", editRow);
             }
             //当无编辑行时
             if (editRow == undefined) {
               //获取到当前选择行的下标
               var index = datagrid.datagrid("getRowIndex", rows[0]);
               //开启编辑
               datagrid.datagrid("beginEdit", index);
               //把当前开启编辑的行赋值给全局变量editRow
               editRow = index;
               //当开启了当前选择行的编辑状态之后,
               //应该取消当前列表的所有选择行,要不然双击之后无法再选择其他行进行编辑
               datagrid.datagrid("unselectAll");
             }
           }
         }
       }, '-',
       {
         text: '保存', iconCls: 'icon-save', handler: function () {
           //保存时结束当前编辑的行,自动触发onAfterEdit事件如果要与后台交互可将数据通过Ajax提交后台
           datagrid.datagrid("endEdit", editRow);
         }
       }, '-',
       {
         text: '取消编辑', iconCls: 'icon-redo', handler: function () {
           //取消当前编辑行把当前编辑行罢undefined回滚改变的数据,取消选择的行
           editRow = undefined;
           datagrid.datagrid("rejectChanges");
           datagrid.datagrid("unselectAll");
         }
       }, '-'],
      onAfterEdit: function (rowIndex, rowData, changes) {
        //endEdit该方法触发此事件
        //console.info(rowData);
        //---- Update(ids.join(','));//这是post
        editRow = undefined;
      },
      onDblClickRow: function (rowIndex, rowData) {
        //双击开启编辑行
        if (editRow != undefined) {
          datagrid.datagrid("endEdit", editRow);
        }
        if (editRow == undefined) {
          datagrid.datagrid("beginEdit", rowIndex);
          editRow = rowIndex;
        }
      }
    });
  });

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
js 省地市级联选择
Feb 07 Javascript
jQuery Form 页面表单提交的小例子
Nov 15 Javascript
Node.js中安全调用系统命令的方法(避免注入安全漏洞)
Dec 05 Javascript
jQuery中size()方法用法实例
Dec 27 Javascript
javascript如何写热点图
Dec 08 Javascript
jQuery添加options点击事件并传值实例代码
May 18 Javascript
JS实现可编辑的后台管理菜单功能【附demo源码下载】
Sep 13 Javascript
AngularJS中的DOM操作用法分析
Nov 04 Javascript
浅谈 vue 中的 watcher
Dec 04 Javascript
Bootstrap的aria-label和aria-labelledby属性实例详解
Nov 02 Javascript
JQuery获取可视区尺寸和文档尺寸及制作悬浮菜单示例
May 14 jQuery
vue实现评论列表功能
Oct 25 Javascript
浅谈javascript的闭包
Jan 23 #Javascript
JS复制对应id的内容到粘贴板(Ctrl+C效果)
Jan 23 #Javascript
JavaScript常用正则验证函数实例小结【年龄,数字,Email,手机,URL,日期等】
Jan 23 #Javascript
Node.js Express 框架 POST方法详解
Jan 23 #Javascript
js 颜色选择插件
Jan 23 #Javascript
JavaScript常用正则函数用法示例
Jan 23 #Javascript
详解微信小程序 wx.uploadFile 的编码坑
Jan 23 #Javascript
You might like
php和数据库结合的一个简单的web实例 代码分析 (php初学者)
2011/07/28 PHP
Linux下php5.4启动脚本
2014/08/03 PHP
PHP入门教程之面向对象基本概念实例分析
2016/09/11 PHP
PHP与JavaScript针对Cookie的读写、交互操作方法详解
2017/08/07 PHP
[原创]js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结
2007/03/12 Javascript
JS getMonth()日期函数的值域是0-11
2010/02/15 Javascript
jQuery学习笔记之jQuery的DOM操作
2010/12/22 Javascript
javascript制作的滑动图片菜单
2015/05/15 Javascript
js+HTML5实现canvas多种颜色渐变效果的方法
2015/06/05 Javascript
JS实现的表格行上下移动操作示例
2016/08/03 Javascript
Vue.js动态添加、删除选题的实例代码
2016/09/30 Javascript
使用Bootstrap Tabs选项卡Ajax加载数据实现
2016/12/23 Javascript
JS实现一个简单的日历
2017/02/22 Javascript
jQuery UI Grid 模态框中的表格实例代码
2017/04/01 jQuery
使用Node.js实现一个多人游戏服务器引擎
2019/03/13 Javascript
详解vue-property-decorator使用手册
2019/07/29 Javascript
python 字符串split的用法分享
2013/03/23 Python
使用python提取html文件中的特定数据的实现代码
2013/03/24 Python
详尽讲述用Python的Django框架测试驱动开发的教程
2015/04/22 Python
[原创]教女朋友学Python3(二)简单的输入输出及内置函数查看
2017/11/30 Python
python复制文件到指定目录的实例
2018/04/27 Python
Sanic框架路由用法实例分析
2018/07/16 Python
python中下标和切片的使用方法解析
2019/08/27 Python
css3进行截取替代js的substring
2013/09/02 HTML / CSS
HTML5 textarea高度自适应的两种方案
2020/04/08 HTML / CSS
New Era英国官网:美国棒球帽品牌
2018/03/21 全球购物
在线购买世界上最好的酒:BoozeBud
2018/06/07 全球购物
澳大利亚最受欢迎的美发和美容在线商店:Catwalk
2018/12/12 全球购物
不开辟用于交换数据的临时空间,如何完成字符串的逆序
2012/12/02 面试题
园长自我鉴定
2013/10/06 职场文书
人事专员职责
2014/02/22 职场文书
学生夜不归宿检讨书
2014/09/23 职场文书
群众路线教育实践活动民主生活会个人检查对照思想汇报
2014/10/04 职场文书
2015新学期开学寄语
2015/02/26 职场文书
大学开学典礼新闻稿
2015/07/17 职场文书
高中美术教学反思
2016/02/17 职场文书