来自 新葡亰数据库 2019-11-08 16:41 的文章
当前位置: 澳门新葡亰app > 新葡亰数据库 > 正文

【澳门新葡亰app】JS脚本部分,列出表格信息

引进EasyUi所有须要的脚本,样式 

相通在上大器晚成节中讲到能够编写的表格,未来讲平时用到的末梢三个datagrid(表格卡塔 尔(英语:State of Qatar)相关的开展明细可编写制定的表格;

<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>

其三中表格首要使用途景在:列出表格音信,然后点击可以查看详细消息(此处是整个能够编写,能够改写卡塔尔,举个例证,人士音讯有多数字段,可是日常在列表消息只展现人士相关的最主要字段,可是借使想看人士具有音信的话,就可通过这几个法子来落实,声惠氏点,这里的是能够编写的,你能够做成不可编辑;

JS脚本部分

更况且两句,比方在首先节的时候,如果只提供一张表格表单,举办增添新闻,然后在列表页中列出人士音讯,列出的人口音信不允许编辑,只好够查阅,就可以使用这节的表格;

澳门新葡亰app 1澳门新葡亰app 2

开首任务:

  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卡塔 尔(英语:State of Qatar);

View Code

然后新建二个index.php,将js文件引进;

HTML部分

后台代码应用第2节的,不须求校正,不做牵线;

澳门新葡亰app 3澳门新葡亰app 4

率先步,先看作用图:

 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>

  实行明细,可编写制定(你能够改写成不足订正,只可以够看卡塔尔国

View Code 

澳门新葡亰app 5

后台.NetMVC代码

  增加明细视图:

澳门新葡亰app 6澳门新葡亰app 7

澳门新葡亰app 8

  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页面代码

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>

运营后的效果与利益

 

澳门新葡亰app 9

 首先看table部分,url自动须要地址获取客户新闻列表数据显示,pagination="true"表示带分页,然后正是toolbar下的三个办法newItem()和destroyItem(),个中destroyItem()方法和前面率先节的肖似;

计算:首借使用到了EasyUIDatagrid中 ,编辑结束后事件onAfter艾德it,加多和立异在这里处编写(从上叁遍的提交获取具备行,类型参数有,inserted,deleted,updated 重返的三个数组编辑后的数据卡塔 尔(英语:State of Qatar) 

接下来大家看javascript部分的生龙活虎段代码:这种格式记住,精晓,直接拿来用就足以,使用 'detailFormatter' 函数来生成行明细内容,当顾客点击行展开开关('+'卡塔尔时,'onExpandRow' 事件将被触发,大家将因而 ajax 加载编辑表单(form卡塔 尔(阿拉伯语:قطر‎。 调用 'getRowDetail' 方法来赢得行明细容器,在行明细中创造面板(panel卡塔 尔(阿拉伯语:قطر‎,加载从 'show_form.php' 重回的编排表单;

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

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

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>

 

 

 

第四步:完成saveItem(),cancelItem(),newItem(),destroyItem()八个情势

实现newItem()方法:

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

appendRow追加二个新行。新行将被增添到最终的岗位,给他叁个{isNewRecord:true}属性,能够在saveItem方法中判定,

getRows再次回到当前抱有行;

 

实现saveItem()方法:

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');
        }
    });
}

实现cancelItem()方法:

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

实现destroyItem()方法:

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);
                });
            }
        });
    }
}

 

末尾附上源码:

datagrid-detailview.js

澳门新葡亰app 10澳门新葡亰app 11

$.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;
        }
    }
});

View Code

 

show_form.php

澳门新葡亰app 12澳门新葡亰app 13

<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

 

bus_pubuser.js

/*****************开始 表格显示明细编辑*******************/
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);
}

 

index.php

澳门新葡亰app 14澳门新葡亰app 15

<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>

View Code

 

本文由澳门新葡亰app发布于新葡亰数据库,转载请注明出处:【澳门新葡亰app】JS脚本部分,列出表格信息

关键词: