澳门新葡萄京娱乐网站-澳门新葡萄京888官网-所有平台

热门关键词: 澳门新葡萄京娱乐网站,澳门新葡萄京888官网

EasyuiDatagird绑定分页,CRUD可成立张开发银行明细

作者: MySQL数据库  发布:2019-12-11

引进EasyUi全数必要的本子,样式 

大器晚成致在上风流浪漫节中讲到能够编写制定的报表,以往讲平日用到的末尾多少个datagrid(表格)相关的实行明细可编制的报表;

     相当久未有展开本身的博客园,刚刚大约扫了一眼小编此前写的笔记,关于Devexpress那篇居然有八千多的浏览记录,不掌握对浏览过的博友有未有起到一丝丝功效。当然笔者写笔记仅仅只是给和睦留个回想,假若误打误撞扶持了您,那是很安详的哎!哈哈……明天又来做笔记了!

<link href="/easyui/themes/default/easyui.css" rel="stylesheet" />
<link href="/easyui/themes/icon.css" rel="stylesheet" />
<script src="/easyui/jquery.min.js"></script>
<script src="/easyui/jquery.easyui.min.js"></script>
<script src="/easyui/locale/easyui-lang-zh_CN.js"></script>

其三中表格首要行使场景在:列出表格音讯,然后点击能够查看详细音信(此处是整个能够编写,能够改写),举个例证,职员新闻有无数字段,然则平时在列表新闻只显示职员相关的显要字段,但是借使想看人士具有新闻的话,就可通过这一个主意来落到实处,声明一(Wissu卡塔尔(قطر‎点,这里的是足以编制的,你能够做成不可编辑;

     近日情状有个web项目供给用到第三方控件(EasyUi卡塔尔国,用第三方控件做出来的成效究竟比原生态的要多少美观那么一些,该类型中有个要求,供给在数量列表中央行政机关接编辑数据保存,行话叫做行内编辑。

JS脚本部分

况兼两句,比方在率先节的时候,倘若只提供一张表格表单,举办加多新闻,然后在列表页中列出职员消息,列出的人手音信不容许编辑,只好够查阅,就足以行使那节的报表;

   在讲行内编写制定以前,我们须要先领悟哪些采纳EasyUi创造三个DataGrid,当然格局有为数不菲(1.easyui.js,可能直接html代码加easyui的Style),笔者利用的是JS的办法:

澳门新葡萄京888官网 1澳门新葡萄京888官网 2

最早职分:

   一、使用Js创建DataGrid

  1 <script type="text/javascript">
  2     $(function () {
  3         obj = {
  4             editRow: undefined, 
  5             add: function () {
  6       
  7                 $('#save,#redo').show();
  8                 if (this.editRow == undefined)
  9                  {
 10                     /*appenRow  在末尾添加一行*/
 11                     $('#box').datagrid('insertRow', {
 12                         index: 0,
 13                         row: {
 14                             cityname: '',
 15                             intro: '',
 16                             code: '',
 17                         }
 18                     });
 19                     //将第一行设置为可编辑状态
 20                     $("#box").datagrid('beginEdit', 0),
 21                    this.editRow =0 ;
 22 
 23                 }
 24             },
 25          
 26             edit:function()
 27             {
 28                 var rows = $('#box').datagrid('getSelections');
 29                 if (rows.length == 1) {
 30                     if (this.editRow != undefined) {
 31 
 32                         $("#box").datagrid('endEdit', this.editRow)
 33 
 34                     }
 35                     if (this.editRow == undefined) {
 36                         var index=$("#box").datagrid('getRowIndex',rows[0])
 37                         $('#save,#redo').show();
 38                         $("#box").datagrid('beginEdit', index)
 39                         this.editRow = index
 40                         //关闭当前行编辑状态
 41                         $("#box").datagrid('unselectRow',index)
 42                     }
 43                 }
 44                 else {
 45                     $.messager.alert('警告', '修改只能选中一行','warning');
 46                 }
 47                 
 48             },
 49             /*删除*/
 50             remove:function()
 51             {
 52                 var rows = $('#box').datagrid('getSelections');
 53                 if (rows.length > 0) {
 54                     $.messager.confirm('确定操作', '您确定要删除所选中的记录吗', function (flag) {
 55                         if (flag)
 56                         {
 57                             var ids = [];
 58                             for (var i = 0; i < rows.length; i++)
 59                             {
 60                                 ids.push(rows[i].cid);
 61                             }
 62                             $.ajax(
 63                                 {
 64                                     url: "/cityManager/cityRemove",
 65                                     data:{"ids":ids.join(',')},
 66                                     type: "post",
 67                                     success: function (data)
 68                                     {
 69                                         if (data.Message == "Success")
 70                                         {
 71                                             $("#box").datagrid("loaded");
 72                                             $("#box").datagrid("load");
 73                                             $("#box").datagrid("unselectAll");
 74                                             $.messager.show({
 75                                                 title: '提示',
 76                                                 msg:data.flag+'个信息被删除成功!',
 77                                             })
 78                                         }
 79                                     },
 80                                     error: function (data)
 81                                     {
 82                                         $.messager.alert(data);
 83                                     }
 84                                 });
 85                                  obj.editRow = undefined;
 86                         }
 87                     }
 88                     )
 89                 }
 90                 else {
 91                     $.messager.alert('警告','请选中一行或多行','info')
 92 
 93                 }
 94             },
 95             save: function ()
 96             {
 97                 //这两句不应该放这里,应该是保存之后放这里
 98                 //$('#save,#redo').hide();
 99                 //this.editRow = false;
100                 //将第一行设置为结束编辑
101                 //保存当前行的数据结束编辑     
102                 $("#box").datagrid('endEdit', this.editRow)
103              
104             },
105             redo: function ()
106             {
107                 $('#save,#redo').hide();
108                 this.editRow = undefined;
109                 /*回滚所有从创建或上一次调用acceptChanges函数后更该的数据*/
110                $("#box").datagrid('rejectChanges')
111             }
112         };  
113         /*加载表格*/
114         $("#box").datagrid({
115             url: '/cityManager/cityQuery',
116             singleSelect: false,//多选
117             pagination: true,//分页
118             pageSize: 10,//页面大小
119             pageList: [5, 10, 15, 20, 30, 50, 80, 200],
120             rownumbers:true,//编号
121             title: "城市信息",
122             //右击表格事件
123             onRowContextMenu:function(e,rowIndex,rowData)
124             {
125                 /*去掉默认的右击的面板*/
126                 e.preventDefault();
127                 /*显示Menu锁定位置*/
128                 $('#menu').menu('show', {
129                     left: e.pageX,
130                     top: e.pageY,
131 
132                 })
133             },
134 
135             //双击选中行执行的事件(索引行,数据)
136             onDblClickRow: function (rowIndex, rowData) {  
137                 //将上一次编辑行关闭并且保存        
138                 if (obj.editRow!=undefined) {
139                     $("#box").datagrid('endEdit', obj.editRow);
140                     
141                 }
142                 if (obj.editRow == undefined) {
143                     $('#save,#redo').show();
144                     $("#box").datagrid('beginEdit', rowIndex);
145                     obj.editRow = rowIndex;
146                 }
147             },
148             
149             //编辑结束后事件 *添加和跟新的操作在这了*/
150           onAfterEdit:function(rowIndex,rowDate,changes)
151           {
152               var url = '';
153               var info = '';
154               /*从上一次的提交获取所有行,类型参数有,inserted,deleted,updated
155               返回的一个数组 */           
156               var inserted = $("#box").datagrid('getChanges', 'inserted');
157               var updated = $("#box").datagrid('getChanges', 'updated');
158               /*添加*/
159                if (inserted.length> 0)
160                 {
161                     url = '/cityManager/addCity';
162                    info = '添加';
163                }
164               /*更新*/
165                 if (updated.length > 0)
166                 {
167                     url = '/cityManager/EditCity';
168                     var info = '更新';
169                 }
170                 $.ajax(
171                     {
172                         url: url,
173                         data: rowDate,
174                         type: "post",
175                         success: function (data) {
176                             if (data.Message == "Success") {
177                                 $("#box").datagrid("loaded");//重新加载
178                                 $("#box").datagrid("load");//加载
179                                 $("#box").datagrid("unselectAll");//去掉所有复选框
180                                 $.messager.show({
181                                     title: '提示',
182                                     msg: data.flag + '个信息被"'+info+'"成功!',
183                                 })                   
184                             }
185                         },
186                         error: function (data) {
187                             $.messager.alert(data);
188                         }
189                     });
190                 $('#save,#redo').hide();
191                 obj.editRow = undefined;//将对象重新赋值为undefined                        
192             },        
193           columns: [[
194               {
195                   field: "cid",
196                   title: "编号",   
197                   align: 'center',
198                   width: 300,
199                   checkbox:true
200               },
201                 {
202                     field: "cityname",
203                     title: "城市名称",
204                     //   hidden: true 隐藏列
205                     align: 'center',
206                     width: 300,
207                     editor: {
208                         type: 'validatebox',
209                         options: {
210                             required:true,
211                         }
212                     }
213                 },
214                 {
215                     field: "intro",
216                     title: "介绍",     
217                     align: 'center',
218                     width: 100,
219                     editor: {  //设置为编辑行
220                         type: 'validatebox',
221                         options: {
222                             required: true,
223                         }
224                     }
225                 },
226             {
227                 field: "code",
228                 title: "代码",
229                 align: 'center',
230                 width: 100,
231                 editor: {  //
232                     type: 'validatebox',
233                     options: {
234                         required: true,
235                     }
236                 }
237             },
238             {
239                 field: "createtime",
240                 title: "创建时间",
241                 align: 'center',
242                 width: 100,
243                 editor: {  //
244                     type: 'datetimebox',
245                     options: {
246                         required: true,
247                     }
248                 }
249             },
250             ]],
251             toolbar: "#tb",
252         })   
253     })
254 </script>

第后生可畏在英特网下载datagrid-detailview.js文件(稍后附出代码文件的js);

澳门新葡萄京888官网 3

View Code

接下来新建贰个index.php,将js文件引进;

上面是效果与利益图,

HTML部分

后台代码应用首节的,不需求校正,不做牵线;

Html代码如下:在页面定义三个table

澳门新葡萄京888官网 4澳门新葡萄京888官网 5

率先步,先看效用图:

澳门新葡萄京888官网 6澳门新葡萄京888官网 7

 1 <table id="box"> </table>
 2 <div id="tb" style="padding:5px;height:auto">
 3     <div style="margin-bottom:5px">
 4         <a href="#" class="easyui-linkbutton" onclick="obj.add();" iconcls="icon-add" plain="true">添加</a>
 5         <a href="#" class="easyui-linkbutton" onclick="obj.edit();" iconcls="icon-edit" plain="true">修改</a>
 6         <a href="#" class="easyui-linkbutton" onclick="obj.remove();" iconcls="icon-remove" plain="true">删除</a>
 7         <a href="#" class="easyui-linkbutton" iconcls="icon-save" style="display:none" id="save" onclick="obj.save()" plain="true">保存</a>
 8         <a href="#" class="easyui-linkbutton" iconcls="icon-redo" style="display:none" id="redo" onclick="obj.redo()" plain="true">取消编辑</a>
 9     </div>  
10 </div>
11 <div id="menu" class="easyui-menu" style="width:100px;display:none">
12     <div onclick="obj.add();" iconcls="icon-add" plain="true">添加</div>
13     <div onclick="obj.edit();" iconcls="icon-edit" plain="true">修改</div>
14     <div onclick="obj.remove();" iconcls="icon-remove" plain="true">删除</div>
15 </div>

  进行明细,可编写制定(你可以改写成不足校订,只好够看)

1 <!--数据展示 -->
2 <div>
3     <table id="DataGridInbound"></table>
4 </div>

View Code 

澳门新葡萄京888官网 8

View Code

后台.NetMVC代码

  增多明细视图:

 Js代码如下:

澳门新葡萄京888官网 9澳门新葡萄京888官网 10

澳门新葡萄京888官网 11

 有多少个自己自身感到超级重大的特性在那标记下

  1       /*查询*/
  2         public ActionResult cityQuery()
  3         {
  4             //获取分页的页数
  5             int pageNum = Convert.ToInt32(Request.Params["page"]);
  6             //获取分页大小
  7             int pageSize = Convert.ToInt32(Request.Params["rows"]);
  8             var CityList = (from u in db.tb_city
  9                           orderby u.cid descending
 10                           where(u.isdelete==0)
 11                           select u).Skip(pageSize * (pageNum - 1)).Take(pageSize);
 12             //     using Newtonsoft.Json 序列化转成Json字符串
 13             var jsons = JsonConvert.SerializeObject(CityList);
 14     
 15             string json = "{"total":" + db.tb_city.ToList().Count + ","rows": " + jsons + "}";
 16             return Content(json); 
 17         }
 18         /*删除*/
 19         public ActionResult cityRemove()
 20         {
 21     
 22             Hashtable ht = new Hashtable();
 23             string[] ids = ConvertHelper.GetString(Request["ids"]).Split(',');
 24             int flag = 0;
 25             foreach (var item in ids)
 26             {
 27                 tb_city model = db.tb_city.Find(ConvertHelper.GetInteger(item));
 28                 model.isdelete =1;
 29                 TryUpdateModel(model);
 30                 db.SaveChanges();
 31                 flag++;      
 32             }
 33             if (flag > 0)
 34             { 
 35               ht["Message"] = "Success";
 36               ht["flag"] = flag;
 37               ht["Resulet"] = true;
 38             }
 39             else
 40             {
 41              ht["Message"] = "Error";
 42              ht["Resulet"] = false;
 43             }
 44 
 45 
 46             return Json(ht);
 47           
 48         }
 49         /*添加*/
 50         public ActionResult addCity()
 51         {
 52             Hashtable ht = new Hashtable();
 53             string cityname = ConvertHelper.GetString(Request["cityname"]);
 54             string code = ConvertHelper.GetString(Request["code"]);
 55             string intro = ConvertHelper.GetString(Request["cityname"]);  
 56             tb_city model = new tb_city();
 57             model.cityname = cityname;
 58             model.code = code;
 59             model.intro = intro;
 60              model.isdelete = 0;
 61              db.tb_city.Add(model);
 62             int flag= db.SaveChanges();
 63    
 64           
 65             if (flag > 0)
 66             {
 67                 ht["Message"] = "Success";
 68                 ht["flag"] = flag;    
 69                 ht["Resulet"] = true;
 70             }
 71             else
 72             {
 73                 ht["Message"] = "Error";
 74                 ht["Resulet"] = false;
 75             }
 76             return Json(ht);
 77 
 78         }
 79 
 80         /*修改*/
 81         public ActionResult EditCity()
 82         {
 83             Hashtable ht = new Hashtable();
 84             string id = ConvertHelper.GetString(Request["cid"]);
 85             string cityname = ConvertHelper.GetString(Request["cityname"]);
 86             string code = ConvertHelper.GetString(Request["code"]);
 87             string intro = ConvertHelper.GetString(Request["cityname"]);
 88            string user = ConvertHelper.GetString(Request["cityname"]);
 89            tb_city model = db.tb_city.Find(ConvertHelper.GetInteger(id));
 90             model.cityname = cityname;
 91             model.code = code;
 92             model.intro = intro;
 93              model.isdelete = 0;
 94              TryUpdateModel(model);
 95             int flag= db.SaveChanges();
 96    
 97           
 98             if (flag > 0)
 99             {
100                 ht["Message"] = "Success";
101                 ht["flag"] = flag;    
102                 ht["Resulet"] = true;
103             }
104             else
105             {
106                 ht["Message"] = "Error";
107                 ht["Resulet"] = false;
108             }
109             return Json(ht);
110 
111         }

 第二步:编写index.php页面代码

url:这里是datagrid获取数据集之处,就是您的Action,必要专一的是,你的Action供给重返Json格式的数额。

View Code

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>创建展开行明细编辑表单</title>
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/color.css">
    <script src="../ui/jquery-easyui-1.4.5/jquery.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
    <script src="../js/crud/datagrid-detailview.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/locale/easyui-lang-zh_CN.js"></script>
    <script src="../js/crud/bus_pubuser.js"></script>
    <script>
    $(function(){
        $('#dg').datagrid({
            view: detailview,
            detailFormatter:function(index,row){
                return '<div class="ddv"></div>';
            },
            onExpandRow: function(index,row){
                var ddv = $(this).datagrid('getRowDetail',index).find('div.ddv');
                ddv.panel({
                    border:false,
                    cache:true,
                    href:'./page/show_form.php?index='+index,
                    onLoad:function(){
                        $('#dg').datagrid('fixDetailRowHeight',index);
                        $('#dg').datagrid('selectRow',index);
                        $('#dg').datagrid('getRowDetail',index).find('form').form('load',row);
                    }
                });
                $('#dg').datagrid('fixDetailRowHeight',index);
            }
        });

    });
    </script>
</head>
<body>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:list
    -->
    <table id="dg" title="用户列表" class="easyui-datagrid" url="./data/crud/userAction.php?flag=list"  style="width:100%;height: 600px;"  toolbar="#toolbar" rownumbers="true" pagination="true"  fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50" >名</th>
                <th field="lname" width="50" >姓</th>
                <th field="sex" width="50" >性别</th>
                <th field="phone" width="50" >联系电话</th>
                <th field="email" width="50" >邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
           <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newItem()">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyItem()">删除</a>
    </div>
</body>
<html>

pagination:设置datagrid是或不是分页展现

运行后的效果

 

queryParams:你的询问条件参数

澳门新葡萄京888官网 12

 首先看table部分,url自动哀告地址获取客商消息列表数据展现,pagination="true"表示带分页,然后正是toolbar下的八个办法newItem(卡塔尔国和destroyItem(卡塔尔,当中destroyItem(卡塔尔(قطر‎方法和前边率先节的同等;

formatter:格式化,在日期列用到了,EasyUi的datagrid显示日期假如不格式话,日期会乱呈现

总计:重假如用到了EasyUIDatagrid中 ,编辑截至后事件onAfterEdit,增加和改善在此边编写(从上叁遍的交给获取具备行,类型参数有,inserted,deleted,updated 再次回到的三个数组编辑后的数额) 

下一场我们看javascript部分的黄金年代段代码:这种格式记住,通晓,直接拿来用就能够,使用 'detailFormatter' 函数来生成行明细内容,当客商点击行张开按键('+')时,'onExpandRow' 事件将被触发,我们将由此 ajax 加载编辑表单(form)。 调用 'getRowDetail' 方法来拿到行明细容器,在行明细中创造面板(panel),加载从 'show_form.php' 再次回到的编纂表单;

那一个属性在EasyUi的官方网址都有详尽介绍,笔者就不深入解释了。

var inserted = $("#box").datagrid('getChanges', 'inserted');  

第三步:编写show_form.php即明细行表单

澳门新葡萄京888官网 13澳门新葡萄京888官网 14

var updated = $("#box").datagrid('getChanges', 'updated'); 

<form method="post">
    <table class="dv-table" style="width:100%;background:#fafafa;padding:5px;margin-top:5px;">
        <tr>
            <td>名</td>
            <td><input name="fname" class="easyui-validatebox" required="true"></input></td>
            <td>姓</td>
            <td><input name="lname" class="easyui-validatebox" required="true"></input></td>
        </tr>
        <tr>
            <td>性别</td>
            <td colspan="3"><input name="sex" class="easyui-validatebox" required="true"></input></td>
        </tr>
        <tr>
            <td>电话</td>
            <td><input name="phone"></input></td>
            <td>邮件</td>
            <td><input name="email" class="easyui-validatebox" validType="email"></input></td>
        </tr>
    </table>
    <div style="padding:5px 0;text-align:right;padding-right:30px">
        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="saveItem(<?php echo $_REQUEST['index'];?>)">Save</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="cancelItem(<?php echo $_REQUEST['index'];?>)">Cancel</a>
    </div>
</form>
 1 $("#DataGridInbound").datagrid({
 2             title: '入库详情',
 3             idField: 'Id',
 4             rownumbers: 'true',
 5             url: '/Inbound/GetPageInboundGoodsDetail',
 6             pagination: true,//表示在datagrid设置分页              
 7             rownumbers: true,
 8             singleSelect: true,
 9             striped: true,
10             nowrap: true,
11             collapsible: true,
12             fitColumns: true,
13             remoteSort: false,
14             loadMsg: "正在努力加载数据,请稍后...",
15             queryParams: { ProductName: "", Status: "",SqNo:"" },
16             onLoadSuccess: function (data) {
17                 if (data.total == 0) {
18                     var body = $(this).data().datagrid.dc.body2;
19                     body.find('table tbody').append('<tr><td width="' + body.width() + '" style="height: 35px; text-align: center;"><h1>暂无数据</h1></td></tr>');
20                     $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').hide();
21                 }
22                     //如果通过调用reload方法重新加载数据有数据时显示出分页导航容器
23                 else $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').show();
24             },
25             columns: [[
26                 { field: 'ck', checkbox: true },
27                 { field: 'Id', hidden: 'true' },
28                 { field: 'InBoundId', hidden: 'true' },
29                 { field: 'ProductId', hidden: 'true' },
30                 { field: 'ProductTypeId', hidden: 'true' },
31                 { field: 'SqNo', title: '入库参考号', width: '100', align: 'left', sortable: true },
32                 {
33                     field: 'Status', title: '状态', width: '100', align: 'left', sortable: true,
34                     formatter: function (value, index, row) {
35                         if (value == "1") {
36                             return '已入库';
37                         }
38                         else if (value == "-1") {
39                             return '待入库';
40                         }
41                     }
42                 },
43                 {
44                     field: 'InboundDate', title: '入库日期', width: '100', align: 'left', sortable: true,                   
45                     formatter: function (date) {
46                         var pa = /.*((.*))/;
47                         var unixtime = date.match(pa)[1].substring(0, 10);  //通过正则表达式来获取到时间戳的字符串
48                         return getTime(unixtime);
49                     }
50                 },
51                 { field: 'ProductName', title: '产品名称', width: '100', align: 'left', sortable: true },
52                 { field: 'ProductType', title: '产品类型', width: '100', align: 'left', sortable: true },
53                 { field: 'Num', title: '数量', width: '100', align: 'left', sortable: true },
54                 { field: 'Storage', title: '所属仓库', width: '100', align: 'left', sortable: true },
55                 { field: 'CompanyCode', title: '所属公司', width: '100', align: 'left', sortable: true },
56                 { field: 'CreateBy', title: '操作人', width: '100', align: 'left', sortable: true },
57             ]],
58         });

 

 

View Code

 

 

第四步:实现saveItem(卡塔尔国,cancelItem(卡塔尔(英语:State of Qatar),newItem(卡塔尔(قطر‎,destroyItem(卡塔尔四个艺术

二、后日的尤为重要,DataGrid行内编辑

实现newItem()方法:

澳门新葡萄京888官网 15

function newItem(){
    $('#dg').datagrid('appendRow',{isNewRecord:true});
    var index = $('#dg').datagrid('getRows').length - 1;
    $('#澳门新葡萄京888官网,dg').datagrid('expandRow', index);
    $('#dg').datagrid('selectRow', index);
}

如上效果图,大家在DataGrid行内直接变多少

appendRow追加三个新行。新行将被增添到最终的职位,给她叁个{isNewRecord:true}属性,能够在saveItem方法中推断,

Js代码如下:

getRows再次回到当前全数行;

哪些促成行内编辑,要求在你所编纂的单元格中投入editor属性,editor属性有个type(他扶持广大控件类型,能够到官方网址查阅)就是编辑的控件类型。

 

比如,上海教室中“入库状态”,首先大家定义数据源,json格式是根本。

实现saveItem()方法:

澳门新葡萄京888官网 16澳门新葡萄京888官网 17

function saveItem(index){
    var row = $('#dg').datagrid('getRows')[index];
    var urladd = './data/crud/userAction.php?flag=add';
    var urlmodify = './data/crud/userAction.php?flag=modify&id='+row.id;
    var url = row.isNewRecord ? urladd : urlmodify;
    $('#dg').datagrid('getRowDetail',index).find('form').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(data){
            data = eval('('+data+')');
            data.isNewRecord = false;
            $('#dg').datagrid('collapseRow',index);
            $('#dg').datagrid('updateRow',{
                index: index,
                row: data
            });
            $('#dg').datagrid('reload');
        }
    });
}

var InboundStatus = [{ "value": "1", "text": "入库" }, { "value": "-1", "text": "待入库" }];

实现cancelItem()方法:

View Code

function cancelItem(index){
    var row = $('#dg').datagrid('getRows')[index];
    if (row.isNewRecord){
        $('#dg').datagrid('deleteRow',index);
    } else {
        $('#dg').datagrid('collapseRow',index);
    }
}

然后须要格式调换函数,不然你筛选的时候只会来得value值,不是呈现文本值。代码如下:

实现destroyItem()方法:

澳门新葡萄京888官网 18澳门新葡萄京888官网 19

function destroyItem(){
    var row = $('#dg').datagrid('getSelected');
    var url = './data/crud/userAction.php?flag=delete';
    if (row){
        $.messager.confirm('Confirm','你规定要删减【'+row.lname+row.fname+'】么?',function(r卡塔尔国{
            if (r){
                var index = $('#dg').datagrid('getRowIndex',row);
                $.post(url,{id:row.id},function(){
                    $('#dg').datagrid('deleteRow',index);
                });
            }
        });
    }
}

function unitformatter(value, rowData, rowIndex) {
        if (value == 0) {
            return;
        }
        for (var i = 0; i < InboundStatus.length; i++) {
            if (InboundStatus[i].value == value) {
                return InboundStatus[i].text;
            }
        }
    }

 

View Code

谈到底附上源码:

什么把数据源绑定到DataGrid列中,代码如下:

datagrid-detailview.js

formatter:使用大家前边定义的转移格式函数。

澳门新葡萄京888官网 20澳门新葡萄京888官网 21

options:中的data正是大家定义的数据源。

$.extend($.fn.datagrid.defaults, {
    autoUpdateDetail: true  // Define if update the row detail content when update a row
});

var detailview = $.extend({}, $.fn.datagrid.defaults.view, {
    render: function(target, container, frozen){
        var state = $.data(target, 'datagrid');
        var opts = state.options;
        if (frozen){
            if (!(opts.rownumbers || (opts.frozenColumns && opts.frozenColumns.length))){
                return;
            }
        }

        var rows = state.data.rows;
        var fields = $(target).datagrid('getColumnFields', frozen);
        var table = [];
        table.push('<table class="datagrid-btable" cellspacing="0" cellpadding="0" border="0"><tbody>');
        for(var i=0; i<rows.length; i++) {
            // get the class and style attributes for this row
            var css = opts.rowStyler ? opts.rowStyler.call(target, i, rows[i]) : '';
            var classValue = '';
            var styleValue = '';
            if (typeof css == 'string'){
                styleValue = css;
            } else if (css){
                classValue = css['class'] || '';
                styleValue = css['style'] || '';
            }

            var cls = 'class="datagrid-row ' + (i % 2 && opts.striped ? 'datagrid-row-alt ' : ' ') + classValue + '"';
            var style = styleValue ? 'style="' + styleValue + '"' : '';
            var rowId = state.rowIdPrefix + '-' + (frozen?1:2) + '-' + i;
            table.push('<tr id="' + rowId + '" datagrid-row-index="' + i + '" ' + cls + ' ' + style + '>');
            table.push(this.renderRow.call(this, target, fields, frozen, i, rows[i]));
            table.push('</tr>');

            table.push('<tr style="display:none;">');
            if (frozen){
                table.push('<td colspan=' + (fields.length+(opts.rownumbers?1:0)) + ' style="border-right:0">');
            } else {
                table.push('<td colspan=' + (fields.length) + '>');
            }

            table.push('<div class="datagrid-row-detail">');
            if (frozen){
                table.push('&nbsp;');
            } else {
                table.push(opts.detailFormatter.call(target, i, rows[i]));
            }
            table.push('</div>');

            table.push('</td>');
            table.push('</tr>');

        }
        table.push('</tbody></table>');

        $(container).html(table.join(''));
    },

    renderRow: function(target, fields, frozen, rowIndex, rowData){
        var opts = $.data(target, 'datagrid').options;

        var cc = [];
        if (frozen && opts.rownumbers){
            var rownumber = rowIndex + 1;
            if (opts.pagination){
                rownumber += (opts.pageNumber-1)*opts.pageSize;
            }
            cc.push('<td class="datagrid-td-rownumber"><div class="datagrid-cell-rownumber">'+rownumber+'</div></td>');
        }
        for(var i=0; i<fields.length; i++){
            var field = fields[i];
            var col = $(target).datagrid('getColumnOption', field);
            if (col){
                var value = rowData[field];    // the field value
                var css = col.styler ? (col.styler(value, rowData, rowIndex)||'') : '';
                var classValue = '';
                var styleValue = '';
                if (typeof css == 'string'){
                    styleValue = css;
                } else if (cc){
                    classValue = css['class'] || '';
                    styleValue = css['style'] || '';
                }
                var cls = classValue ? 'class="' + classValue + '"' : '';
                var style = col.hidden ? 'style="display:none;' + styleValue + '"' : (styleValue ? 'style="' + styleValue + '"' : '');

                cc.push('<td field="' + field + '" ' + cls + ' ' + style + '>');

                if (col.checkbox){
                    style = '';
                } else if (col.expander){
                    style = "text-align:center;height:16px;";
                } else {
                    style = styleValue;
                    if (col.align){style += ';text-align:' + col.align + ';'}
                    if (!opts.nowrap){
                        style += ';white-space:normal;height:auto;';
                    } else if (opts.autoRowHeight){
                        style += ';height:auto;';
                    }
                }

                cc.push('<div style="' + style + '" ');
                if (col.checkbox){
                    cc.push('class="datagrid-cell-check ');
                } else {
                    cc.push('class="datagrid-cell ' + col.cellClass);
                }
                cc.push('">');

                if (col.checkbox){
                    cc.push('<input type="checkbox" name="' + field + '" value="' + (value!=undefined ? value : '') + '">');
                } else if (col.expander) {
                    //cc.push('<div style="text-align:center;width:16px;height:16px;">');
                    cc.push('');
                    //cc.push('</div>');
                } else if (col.formatter){
                    cc.push(col.formatter(value, rowData, rowIndex));
                } else {
                    cc.push(value);
                }

                cc.push('</div>');
                cc.push('</td>');
            }
        }
        return cc.join('');
    },

    insertRow: function(target, index, row){
        var opts = $.data(target, 'datagrid').options;
        var dc = $.data(target, 'datagrid').dc;
        var panel = $(target).datagrid('getPanel');
        var view1 = dc.view1;
        var view2 = dc.view2;

        var isAppend = false;
        var rowLength = $(target).datagrid('getRows').length;
        if (rowLength == 0){
            $(target).datagrid('loadData',{total:1,rows:[row]});
            return;
        }

        if (index == undefined || index == null || index >= rowLength) {
            index = rowLength;
            isAppend = true;
            this.canUpdateDetail = false;
        }

        $.fn.datagrid.defaults.view.insertRow.call(this, target, index, row);

        _insert(true);
        _insert(false);

        this.canUpdateDetail = true;

        function _insert(frozen){
            var tr = opts.finder.getTr(target, index, 'body', frozen?1:2);
            if (isAppend){
                var detail = tr.next();
                var newDetail = tr.next().clone();
                tr.insertAfter(detail);
            } else {
                var newDetail = tr.next().next().clone();
            }
            newDetail.insertAfter(tr);
            newDetail.hide();
            if (!frozen){
                newDetail.find('div.datagrid-row-detail').html(opts.detailFormatter.call(target, index, row));
            }
        }
    },

    deleteRow: function(target, index){
        var opts = $.data(target, 'datagrid').options;
        var dc = $.data(target, 'datagrid').dc;
        var tr = opts.finder.getTr(target, index);
        tr.next().remove();
        $.fn.datagrid.defaults.view.deleteRow.call(this, target, index);
        dc.body2.triggerHandler('scroll');
    },

    updateRow: function(target, rowIndex, row){
        var dc = $.data(target, 'datagrid').dc;
        var opts = $.data(target, 'datagrid').options;
        var cls = $(target).datagrid('getExpander', rowIndex).attr('class');
        $.fn.datagrid.defaults.view.updateRow.call(this, target, rowIndex, row);
        $(target).datagrid('getExpander', rowIndex).attr('class',cls);

        // update the detail content
        if (opts.autoUpdateDetail && this.canUpdateDetail){
            var row = $(target).datagrid('getRows')[rowIndex];
            var detail = $(target).datagrid('getRowDetail', rowIndex);
            detail.html(opts.detailFormatter.call(target, rowIndex, row));
        }
    },

    bindEvents: function(target){
        var state = $.data(target, 'datagrid');

        if (state.ss.bindDetailEvents){return;}
        state.ss.bindDetailEvents = true;

        var dc = state.dc;
        var opts = state.options;
        var body = dc.body1.add(dc.body2);
        var clickHandler = ($.data(body[0],'events')||$._data(body[0],'events')).click[0].handler;
        body.unbind('click').bind('click', function(e){
            var tt = $(e.target);
            var tr = tt.closest('tr.datagrid-row');
            if (!tr.length){return}
            if (tt.hasClass('datagrid-row-expander')){
                var rowIndex = parseInt(tr.attr('datagrid-row-index'));
                if (tt.hasClass('datagrid-row-expand')){
                    $(target).datagrid('expandRow', rowIndex);
                } else {
                    $(target).datagrid('collapseRow', rowIndex);
                }
                $(target).datagrid('fixRowHeight');

            } else {
                clickHandler(e);
            }
            e.stopPropagation();
        });
    },

    onBeforeRender: function(target){
        var state = $.data(target, 'datagrid');
        var opts = state.options;
        var dc = state.dc;
        var t = $(target);
        var hasExpander = false;
        var fields = t.datagrid('getColumnFields',true).concat(t.datagrid('getColumnFields'));
        for(var i=0; i<fields.length; i++){
            var col = t.datagrid('getColumnOption', fields[i]);
            if (col.expander){
                hasExpander = true;
                break;
            }
        }
        if (!hasExpander){
            if (opts.frozenColumns && opts.frozenColumns.length){
                opts.frozenColumns[0].splice(0,0,{field:'_expander',expander:true,width:24,resizable:false,fixed:true});
            } else {
                opts.frozenColumns = [[{field:'_expander',expander:true,width:24,resizable:false,fixed:true}]];
            }

            var t = dc.view1.children('div.datagrid-header').find('table');
            var td = $('<td rowspan="'+opts.frozenColumns.length+'"><div class="datagrid-header-expander" style="width:24px;"></div></td>');
            if ($('tr',t).length == 0){
                td.wrap('<tr></tr>').parent().appendTo($('tbody',t));
            } else if (opts.rownumbers){
                td.insertAfter(t.find('td:has(div.datagrid-header-rownumber)'));
            } else {
                td.prependTo(t.find('tr:first'));
            }
        }

        // if (!state.bindDetailEvents){
        //     state.bindDetailEvents = true;
        //     var that = this;
        //     setTimeout(function(){
        //         that.bindEvents(target);
        //     },0);
        // }
    },

    onAfterRender: function(target){
        var that = this;
        var state = $.data(target, 'datagrid');
        var dc = state.dc;
        var opts = state.options;
        var panel = $(target).datagrid('getPanel');

        $.fn.datagrid.defaults.view.onAfterRender.call(this, target);

        if (!state.onResizeColumn){
            state.onResizeColumn = opts.onResizeColumn;
        }
        if (!state.onResize){
            state.onResize = opts.onResize;
        }
        function resizeDetails(){
            var ht = dc.header2.find('table');
            var fr = ht.find('tr.datagrid-filter-row').hide();
            var ww = ht.width()-1;
            var details = dc.body2.find('>table.datagrid-btable>tbody>tr>td>div.datagrid-row-detail:visible')._outerWidth(ww);
            // var details = dc.body2.find('div.datagrid-row-detail:visible')._outerWidth(ww);
            details.find('.easyui-fluid').trigger('_resize');
            fr.show();
        }

        opts.onResizeColumn = function(field, width){
            if (!opts.fitColumns){
                resizeDetails();                
            }
            var rowCount = $(target).datagrid('getRows').length;
            for(var i=0; i<rowCount; i++){
                $(target).datagrid('fixDetailRowHeight', i);
            }

            // call the old event code
            state.onResizeColumn.call(target, field, width);
        };
        opts.onResize = function(width, height){
            if (opts.fitColumns){
                resizeDetails();                
            }
            state.onResize.call(panel, width, height);
        };

        this.canUpdateDetail = true;    // define if to update the detail content when 'updateRow' method is called;

        var footer = dc.footer1.add(dc.footer2);
        footer.find('span.datagrid-row-expander').css('visibility', 'hidden');
        $(target).datagrid('resize');

        this.bindEvents(target);
        var detail = dc.body1.add(dc.body2).find('div.datagrid-row-detail');
        detail.unbind().bind('mouseover mouseout click dblclick contextmenu scroll', function(e){
            e.stopPropagation();
        });
    }
});

$.extend($.fn.datagrid.methods, {
    fixDetailRowHeight: function(jq, index){
        return jq.each(function(){
            var opts = $.data(this, 'datagrid').options;
            if (!(opts.rownumbers || (opts.frozenColumns && opts.frozenColumns.length))){
                return;
            }
            var dc = $.data(this, 'datagrid').dc;
            var tr1 = opts.finder.getTr(this, index, 'body', 1).next();
            var tr2 = opts.finder.getTr(this, index, 'body', 2).next();
            // fix the detail row height
            if (tr2.is(':visible')){
                tr1.css('height', '');
                tr2.css('height', '');
                var height = Math.max(tr1.height(), tr2.height());
                tr1.css('height', height);
                tr2.css('height', height);
            }
            dc.body2.triggerHandler('scroll');
        });
    },
    getExpander: function(jq, index){    // get row expander object
        var opts = $.data(jq[0], 'datagrid').options;
        return opts.finder.getTr(jq[0], index).find('span.datagrid-row-expander');
    },
    // get row detail container
    getRowDetail: function(jq, index){
        var opts = $.data(jq[0], 'datagrid').options;
        var tr = opts.finder.getTr(jq[0], index, 'body', 2);
        // return tr.next().find('div.datagrid-row-detail');
        return tr.next().find('>td>div.datagrid-row-detail');
    },
    expandRow: function(jq, index){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var dc = $.data(this, 'datagrid').dc;
            var expander = $(this).datagrid('getExpander', index);
            if (expander.hasClass('datagrid-row-expand')){
                expander.removeClass('datagrid-row-expand').addClass('datagrid-row-collapse');
                var tr1 = opts.finder.getTr(this, index, 'body', 1).next();
                var tr2 = opts.finder.getTr(this, index, 'body', 2).next();
                tr1.show();
                tr2.show();
                $(this).datagrid('fixDetailRowHeight', index);
                if (opts.onExpandRow){
                    var row = $(this).datagrid('getRows')[index];
                    opts.onExpandRow.call(this, index, row);
                }
            }
        });
    },
    collapseRow: function(jq, index){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var dc = $.data(this, 'datagrid').dc;
            var expander = $(this).datagrid('getExpander', index);
            if (expander.hasClass('datagrid-row-collapse')){
                expander.removeClass('datagrid-row-collapse').addClass('datagrid-row-expand');
                var tr1 = opts.finder.getTr(this, index, 'body', 1).next();
                var tr2 = opts.finder.getTr(this, index, 'body', 2).next();
                tr1.hide();
                tr2.hide();
                dc.body2.triggerHandler('scroll');
                if (opts.onCollapseRow){
                    var row = $(this).datagrid('getRows')[index];
                    opts.onCollapseRow.call(this, index, row);
                }
            }
        });
    }
});

$.extend($.fn.datagrid.methods, {
    subgrid: function(jq, conf){
        return jq.each(function(){
            createGrid(this, conf);

            function createGrid(target, conf, prow){
                var queryParams = $.extend({}, conf.options.queryParams||{});
                // queryParams[conf.options.foreignField] = prow ? prow[conf.options.foreignField] : undefined;
                if (prow){
                    var fk = conf.options.foreignField;
                    if ($.isFunction(fk)){
                        $.extend(queryParams, fk.call(conf, prow));
                    } else {
                        queryParams[fk] = prow[fk];
                    }
                }

                var plugin = conf.options.edatagrid ? 'edatagrid' : 'datagrid';

                $(target)[plugin]($.extend({}, conf.options, {
                    subgrid: conf.subgrid,
                    view: (conf.subgrid ? detailview : undefined),
                    queryParams: queryParams,
                    detailFormatter: function(index, row){
                        return '<div><table class="datagrid-subgrid"></table></div>';
                    },
                    onExpandRow: function(index, row){
                        var opts = $(this).datagrid('options');
                        var rd = $(this).datagrid('getRowDetail', index);
                        var dg = getSubGrid(rd);
                        if (!dg.data('datagrid')){
                            createGrid(dg[0], opts.subgrid, row);
                        }
                        rd.find('.easyui-fluid').trigger('_resize');
                        setHeight(this, index);
                        if (conf.options.onExpandRow){
                            conf.options.onExpandRow.call(this, index, row);
                        }
                    },
                    onCollapseRow: function(index, row){
                        setHeight(this, index);
                        if (conf.options.onCollapseRow){
                            conf.options.onCollapseRow.call(this, index, row);
                        }
                    },
                    onResize: function(){
                        var dg = $(this).children('div.datagrid-view').children('table')
                        setParentHeight(this);
                    },
                    onResizeColumn: function(field, width){
                        setParentHeight(this);
                        if (conf.options.onResizeColumn){
                            conf.options.onResizeColumn.call(this, field, width);
                        }
                    },
                    onLoadSuccess: function(data){
                        setParentHeight(this);
                        if (conf.options.onLoadSuccess){
                            conf.options.onLoadSuccess.call(this, data);
                        }
                    }
                }));
            }
            function getSubGrid(rowDetail){
                var div = $(rowDetail).children('div');
                if (div.children('div.datagrid').length){
                    return div.find('>div.datagrid>div.panel-body>div.datagrid-view>table.datagrid-subgrid');
                } else {
                    return div.find('>table.datagrid-subgrid');
                }
            }
            function setParentHeight(target){
                var tr = $(target).closest('div.datagrid-row-detail').closest('tr').prev();
                if (tr.length){
                    var index = parseInt(tr.attr('datagrid-row-index'));
                    var dg = tr.closest('div.datagrid-view').children('table');
                    setHeight(dg[0], index);
                }
            }
            function setHeight(target, index){
                $(target).datagrid('fixDetailRowHeight', index);
                $(target).datagrid('fixRowHeight', index);
                var tr = $(target).closest('div.datagrid-row-detail').closest('tr').prev();
                if (tr.length){
                    var index = parseInt(tr.attr('datagrid-row-index'));
                    var dg = tr.closest('div.datagrid-view').children('table');
                    setHeight(dg[0], index);
                }
            }
        });
    },
    getSelfGrid: function(jq){
        var grid = jq.closest('.datagrid');
        if (grid.length){
            return grid.find('>.datagrid-wrap>.datagrid-view>.datagrid-f');
        } else {
            return null;
        }
    },
    getParentGrid: function(jq){
        var detail = jq.closest('div.datagrid-row-detail');
        if (detail.length){
            return detail.closest('.datagrid-view').children('.datagrid-f');
        } else {
            return null;
        }
    },
    getParentRowIndex: function(jq){
        var detail = jq.closest('div.datagrid-row-detail');
        if (detail.length){
            var tr = detail.closest('tr').prev();
            return parseInt(tr.attr('datagrid-row-index'));
        } else {
            return -1;
        }
    }
});

valueField:选中后的value值,不用精解了呢

View Code

textField:选中后显示的值,文本值。

 

type:combobox,就是下拉筛选的体裁。

show_form.php

澳门新葡萄京888官网 22澳门新葡萄京888官网 23

澳门新葡萄京888官网 24澳门新葡萄京888官网 25

{
                field: 'Status', title: '入库状态', formatter: unitformatter, editor: {
                    type: 'combobox', options: { data: InboundStatus, valueField: "value", textField: "text" }
                }
            },
//这部分代码请结合下面的创建Grid的Js代码查看。
<form method="post">
    <table class="dv-table" style="width:100%;background:#fafafa;padding:5px;margin-top:5px;">
        <tr>
            <td>名</td>
            <td><input name="fname" class="easyui-validatebox" required="true"></input></td>
            <td>姓</td>
            <td><input name="lname" class="easyui-validatebox" required="true"></input></td>
        </tr>
        <tr>
            <td>性别</td>
            <td colspan="3"><input name="sex" class="easyui-validatebox" required="true"></input></td>
        </tr>
        <tr>
            <td>电话</td>
            <td><input name="phone"></input></td>
            <td>邮件</td>
            <td><input name="email" class="easyui-validatebox" validType="email"></input></td>
        </tr>
    </table>
    <div style="padding:5px 0;text-align:right;padding-right:30px">
        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="saveItem(<?php echo $_REQUEST['index'];?>)">Save</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="cancelItem(<?php echo $_REQUEST['index'];?>)">Cancel</a>
    </div>
</form>

View Code

View Code

 

 

澳门新葡萄京888官网 26澳门新葡萄京888官网 27

bus_pubuser.js

$("#dataGrid").datagrid({
        title: "产品列表",
        idField: 'ProductID',
        treeField: 'ProductName',
        onClickCell: onClickCell,
        striped: true,
        nowrap: true,
        collapsible: true,
        fitColumns: true,
        remoteSort: false,
        sortOrder: "desc",
        pagination: true,//表示在datagrid设置分页              
        rownumbers: true,
        singleSelect: false,
        loadMsg: "正在努力加载数据,请稍后...",
        url: "/Inbound/GetProductPage",
        onLoadSuccess: function (data) {
            if (data.total == 0) {
                var body = $(this).data().datagrid.dc.body2;
                body.find('table tbody').append('<tr><td width="' + body.width() + '" style="height: 35px; text-align: center;"><h1>暂无数据</h1></td></tr>');
                $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').hide();
            }
                //如果通过调用reload方法重新加载数据有数据时显示出分页导航容器
            else $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').show();
        },
        columns: [[
            { field: 'ck', checkbox: true },
            { field: 'ProductID', title: '产品ID', hidden: true },
            { field: 'CategoryID', title: '分类ID', hidden: true },
            { field: 'ProductName', title: '产品名称', width: '100', align: 'left', sortable: true },
            { field: 'CompanyCode', title: '所属公司', width: '100', align: 'center', sortable: true },
            { field: 'CategoryName', title: '所属分类', width: '100', align: 'center', sortable: true },
            { field: 'Num', title: '数量', editor: 'numberbox' },
            {
                field: 'Status', title: '入库状态', formatter: unitformatter, editor: {
                    type: 'combobox', options: { data: InboundStatus, valueField: "value", textField: "text" }
                }
            },
           {
               field: 'InDate', title: '入库日期', width: '100', editor: {
                   type: 'datebox'
               }
           },
           {
               field: 'Storage', width: '100', title: '所入仓库',
               formatter: function (value, row) {
                   return row.Storage || value;
               },
               editor: {
                   type: 'combogrid', options: {
                       //url: '/Storage/GetAllStorage',
                       //url:'/Product/GetAllCustomerAddress',
                       rownumbers: true,
                       data: $.extend(true, [], sdata),
                       idField: 'AddressID',
                       textField: 'Name',
                       columns: [[
                           { field: 'AddressID', hidden: true },
                           { field: 'Name', title: '库名' },
                           { field: 'Country', title: '国家' },
                           { field: 'Province', title: '省份' },
                           { field: 'City', title: '市' },
                           { field: 'Area', title: '区' },
                           { field: 'Address', title: '详细地址' },
                       ]],
                       loadFilter: function (sdata) {
                           if ($.isArray(sdata)) {
                               sdata = {
                                   total: sdata.length,
                                   rows: sdata
                               }
                           }
                           return sdata;
                       },
                   }
               }
           }
        ]],
        onBeginEdit: function (index, row) {
            var ed = $(this).datagrid('getEditor', { index: index, field: 'Storage' });
            $(ed.target).combogrid('setValue', { AddressID: row.AddressID, Name: row.Name });
        },
        onEndEdit: function (index, row) {
            var ed = $(this).datagrid('getEditor', { index: index, field: 'Storage' });
            row.Storage = $(ed.target).combogrid('getText');
        },
        onClickRow: function (index, row) {//getEditor
            var ed = $(this).datagrid('getEditor', { index: index, field: 'Storage' });
            if (ed != undefined) {
                var s = row.Storage;
                for (var i = 0; i < sdata.length; i++) {
                    if (s == sdata[i].Name) {
                        $(ed.target).combogrid('setValue', sdata[i].AddressID);
                    }
                }
            }
        }
    });
/*****************开始 表格显示明细编辑*******************/
function saveItem(index){
    var row = $('#dg').datagrid('getRows')[index];
    var urladd = './data/crud/userAction.php?flag=add';
    var urlmodify = './data/crud/userAction.php?flag=modify&id='+row.id;
    var url = row.isNewRecord ? urladd : urlmodify;
    $('#dg').datagrid('getRowDetail',index).find('form').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(data){
            data = eval('('+data+')');
            data.isNewRecord = false;
            $('#dg').datagrid('collapseRow',index);
            $('#dg').datagrid('updateRow',{
                index: index,
                row: data
            });
            $('#dg').datagrid('reload');
        }
    });
}

function cancelItem(index){
    var row = $('#dg').datagrid('getRows')[index];
    if (row.isNewRecord){
        $('#dg').datagrid('deleteRow',index);
    } else {
        $('#dg').datagrid('collapseRow',index);
    }
}



function destroyItem(){
    var row = $('#dg').datagrid('getSelected');
    var url = './data/crud/userAction.php?flag=delete';
    if (row){
        $.messager.confirm('Confirm','你确定要删除【'+row.lname+row.fname+'】么?',function(r){
            if (r){
                var index = $('#dg').datagrid('getRowIndex',row);
                $.post(url,{id:row.id},function(){
                    $('#dg').datagrid('deleteRow',index);
                });
            }
        });
    }
}

function newItem(){
    $('#dg').datagrid('appendRow',{isNewRecord:true});
    var index = $('#dg').datagrid('getRows').length - 1;
    $('#dg').datagrid('expandRow', index);
    $('#dg').datagrid('selectRow', index);
}

View Code

 

三、重头戏,也是自己遇上的主题材料。

index.php

陈说:小编在datagrid中增多了下拉datagrid控件,当本人先是次当选后,假如在去点击datagrid行,选中的下拉datagrid控件的值会被刷掉,那么些标题确实忧虑自个儿十分久,不过新兴管理了,这种感到也是最最的爽啊!

澳门新葡萄京888官网 28澳门新葡萄京888官网 29

澳门新葡萄京888官网 30

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>创建展开行明细编辑表单</title>
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/color.css">
    <script src="../ui/jquery-easyui-1.4.5/jquery.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
    <script src="../js/crud/datagrid-detailview.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/locale/easyui-lang-zh_CN.js"></script>
    <script src="../js/crud/bus_pubuser.js"></script>
    <script>
    $(function(){
//        $('#dg').edatagrid({
//            url: './data/crud/userAction.php?flag=list',
//            saveUrl: './data/crud/userAction.php?flag=add',
//            updateUrl: './data/crud/userAction.php?flag=modify',
//            destroyUrl: './data/crud/userAction.php?flag=delete'
//        });

        $('#dg').datagrid({
            view: detailview,
            detailFormatter:function(index,row){
                return '<div class="ddv"></div>';
            },
            onExpandRow: function(index,row){
                var ddv = $(this).datagrid('getRowDetail',index).find('div.ddv');
                ddv.panel({
                    border:false,
                    cache:true,
                    href:'./page/show_form.php?index='+index,
                    onLoad:function(){
                        $('#dg').datagrid('fixDetailRowHeight',index);
                        $('#dg').datagrid('selectRow',index);
                        $('#dg').datagrid('getRowDetail',index).find('form').form('load',row);
                    }
                });
                $('#dg').datagrid('fixDetailRowHeight',index);
            }
        });

    });
    </script>
</head>
<body>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:list
    -->
    <table id="dg" title="用户列表" class="easyui-datagrid" url="./data/crud/userAction.php?flag=list"  style="width:100%;height: 600px;"  toolbar="#toolbar" rownumbers="true" pagination="true"  fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50" >名</th>
                <th field="lname" width="50" >姓</th>
                <th field="sex" width="50" >性别</th>
                <th field="phone" width="50" >联系电话</th>
                <th field="email" width="50" >邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
           <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newItem()">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyItem()">删除</a>
    </div>
    <!--
        作者:ethancoco
        时间:2016-07-10
        描述:dialog
    -->
    <!--<div id="dlg" class="easyui-dialog" style="width:400px;height:320px;padding:10px 20px;" closed="true" modal="true" buttons="#dlg-buttons">
        <div class="ftitle">基本信息</div>
        <hr />
        <form id="fm" method="post">
            <div class="fitem">
                <p>
                    <label>First Name:</label>
                    <input name="fname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Last Name:</label>
                    <input name="lname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Sex:</label>
                    <input name="sex" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Phone:</label>
                    <input name="phone">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Email:</label>
                    <input name="email" class="easyui-validatebox" validType="email">
                </p>
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    </div>-->
</body>
<html>

如上功用图,“所入酒店”一列,下拉是个datagrid,他的标准词汇叫“Combogird”。正是以此东西第壹遍入选没难点,第一回点击会把第一次当选的值刷掉。那也是一同头自己对EasyUi的二个OnClickRow事件不打听。

View Code

先来上本身事情未发生前的错误代码:

 

澳门新葡萄京888官网 31澳门新葡萄京888官网 32

onClickRow: function (index, row) {//getEditor
            var ed = $(this).datagrid('getEditor', { index: index, field: 'Storage' });

                        $(ed.target).combogrid('setValue', row.Name);
                }
            }
        }

View Code

我们伙一定很忧虑那几个row.Name是个如马玉成西?what?其实本人一齐初也不晓得,因为这几个是错误代码,小编是病笃乱投医,胡乱写的,哈哈,亦不是胡乱写啊,因为本身的下拉grid中有个字段是Name,可是作者把她混淆了,此row是指你点击的datagrid的row,并不是您数据源的row。小编也是再三调节和测量试验Js看出来的端倪。笔者点击datagrid的时候,代码跳入OnClickRow事件中,有句代码:“var ed = $(this卡塔尔(英语:State of Qatar).datagrid('getEditor', { index: index, 田野(field卡塔尔(英语:State of Qatar): 'Storage' }卡塔尔(英语:State of Qatar);”,然后开掘ed为null, Js抛非常,可是界面看不出来,只是把选中的数据刷掉了。找到标题后,照旧不明确,代码改革完,再运营,平常呈现,也不刷掉自家选中的值。

不错代码如下:

澳门新葡萄京888官网 33澳门新葡萄京888官网 34

onClickRow: function (index, row) {//getEditor
            var ed = $(this).datagrid('getEditor', { index: index, field: 'Storage' });
            if (ed != undefined) {
                var s = row.Storage;
                for (var i = 0; i < sdata.length; i++) {
                    if (s == sdata[i].Name) {
                        $(ed.target).combogrid('setValue', sdata[i].AddressID);
                    }
                }
            }
        }

View Code

 一下是下拉Grid的数据源

澳门新葡萄京888官网 35澳门新葡萄京888官网 36

 function synchroAjaxByUrl(url) {
        var temp;
        $.ajax({
            url: url,
            async: false,
            type: 'get',
            dataType: "json",
            success: function (data) {
                temp = data;
            }
        });
        return temp;
    }

    var sdata = synchroAjaxByUrl('/Product/GetAllCustomerAddress');

View Code

难题记下来,仅供参照他事他说加以调查。

本文由澳门新葡萄京娱乐网站发布于MySQL数据库,转载请注明出处:EasyuiDatagird绑定分页,CRUD可成立张开发银行明细

关键词: