jQuery easyUI的datagrid,如何在翻页以后仍能记录被选中的行

1、先给出问题解决后的代码

  1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2 <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
  3 <%
  4 String path = request.getContextPath();
  5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6 %>
  7 
  8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  9 <html>
 10   <head>
 11     <base href="<%=basePath%>">
 12     <title>添加优惠券步骤2</title>
 13     <meta http-equiv="pragma" content="no-cache">
 14     <meta http-equiv="cache-control" content="no-cache">
 15     <meta http-equiv="expires" content="0">    
 16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 17     <jsp:include page="../layout/script.jsp"></jsp:include>
 18     <c:set var="getDataUrl" value="${pageContext.request.contextPath}/goods/getGoodsOnSale" scope="request" />
 19     <script type="text/javascript">
 20             var $dg;
 21             var $grid;
 22             var ids = '';
 23             var idsArray = new Array();
 24             $(function() {
 25                  $dg = $("#dg");
 26                  $grid=$dg.datagrid({
 27                     url : "${getDataUrl}",
 28                     width : 'auto',
 29                     height : $(this).height()-85,
 30                     pagination:true,
 31                     rownumbers:true,
 32                     border:true,
 33                     striped:true,
 34                     singleSelect:false,
 35                     checkOnSelect:true,
 36                     selectOnCheck:true,
 37                     onBeforeLoad:function(data){
 38                         addSelectedGoodsIdToArray();
 39                     },
 40                     onLoadSuccess:function(data){
 41                         var rowsData = data.rows;
 42                         if(idsArray.length!=0){
 43                           $.each(idsArray,function(i,e){
 44                              for(var index=0;index<rowsData.length;index++){
 45                                   if(rowsData[index].goodsId==e){
 46                                        $dg.datagrid('selectRow',index);
 47                                   }
 48                              }
 49                           });
 50                         }
 51                     },
 52                     onUncheck:function(rowIndex,rowData){
 53                         if(idsArray.length == 0){
 54                         }else{
 55                             for(var index=0;index<idsArray.length;index++){
 56                                 if(idsArray[index] == rowData.goodsId){
 57                                     removeArrayValue(idsArray,rowData.goodsId);
 58                                     break;
 59                                 }
 60                             }
 61                         }
 62                     },
 63                     columns : [ [ {field:'ck',checkbox:true},
 64                                   {field : 'goodsId',hidden:true},
 65                                   {field : 'goodsName',title : '商品标题',width : parseInt($(this).width()*0.3)},
 66                                   {field : 'img1',title : '图片',width : parseInt($(this).width()*0.1),align : 'left',
 67                                       formatter:function(value,row){
 68                                           if(row.img1 != '')
 69                                               return "<img src = '"+row.img1+"'/>";
 70                                           else
 71                                               return "<img src = '"+row.img1+"'/>";  
 72                                         }
 73                                   },
 74                                   {field : 'categoryId',title : '分类',width : parseInt($(this).width()*0.1),align : 'left',
 75                                         formatter:function(value,row){
 76                                           var cates = row.categorys;
 77                                           for(var i=0;i<cates.length;i++){
 78                                               if(cates[i].categoryId === row.categoryId){
 79                                                   return cates[i].categoryName;
 80                                               }
 81                                           } 
 82                                         }
 83                                   },
 84                                   {field : 'goodsNumber',title : '库存',width : parseInt($(this).width()*0.1)},
 85                                   {field : 'isOnSale',title : '上架',width :parseInt($(this).width()*0.1),align : 'left',
 86                                       formatter:function(value,row){
 87                                           if(row.isOnSale){
 88                                               return "<font color=green>是<font>";
 89                                           } else{
 90                                               return "<font color=red>否<font>"; 
 91                                           }
 92                                         }
 93                                   },
 94                                   {field : 'lastUpdate',title : '上架时间',width : parseInt($(this).width()*0.1),align : 'left',
 95                                       formatter:function(value,row){
 96                                             var thisDate = new Date(row.lastUpdate);
 97                                               return formatterDate(thisDate);
 98                                       }
 99                                   }
100                                   ] ],toolbar:'#tb'
101                 });
102                 
103                 //搜索框
104                 /* $("#searchbox").searchbox({ 
105                      menu:"#mm", 
106                      prompt :'模糊查询',
107                     searcher:function(value,name){   
108                         var str="{"searchName":""+name+"","searchValue":""+value+""}";
109                         var obj = eval('('+str+')');
110                         $dg.datagrid('reload',obj); 
111                     }
112                    
113                 });  */
114             });
115             
116             function addCheckedGoodIdToArray(rowIndex,rowData){
117                 console.log("_________________________");
118                 var idsArrayLength = idsArray.length;
119                         
120                 if(idsArray.length == 0){
121                     console.log("push:"+rowData.goodsId);
122                     idsArray.push(rowData.goodsId);
123                 }else{
124                     for(var index=0;index<idsArrayLength;index++){
125                         if(idsArray[index] == rowData.goodsId){
126                             console.log("remove:"+rowData.goodsId);
127                             removeArrayValue(idsArray,rowData.goodsId);
128                             break;
129                         }
130                         if(index == idsArrayLength-1){
131                             console.log("push:"+rowData.goodsId);
132                             idsArray.push(rowData.goodsId);
133                         }
134                     }
135                 }
136                 
137                 console.log("---------------");
138                 for(var index=0;index<idsArray.length;index++){
139                     console.log(idsArray[index]);
140                 }
141                 console.log("---------------");
142             }
143             
144             function addSelectedGoodsIdToArray(){
145                 var rows = $dg.datagrid('getSelections');
146                 if(rows.length>0){
147                     $.each(rows,function(i,row){
148                         if(idsArray.length == 0){
149                             idsArray.push(row.goodsId);
150                         }else{
151                             for(var index=0;index<idsArray.length;index++){
152                                 if(idsArray[index] == row.goodsId){
153                                     break;
154                                 }
155                                 if(index == idsArray.length-1){
156                                     idsArray.push(row.goodsId);
157                                     break;
158                                 }
159                             }
160                         }
161                     });
162                 }
163             }
164             
165             function removeSelectedGoodsIdToArray(rows){
166                 //var rows = $dg.datagrid('getSelections');
167                 if(rows.length>0){
168                     $.each(rows,function(i,row){
169                         if(idsArray.length > 0){
170                             for(var index=0;index<idsArray.length;index++){
171                                 removeArrayValue(idsArray,row.goodsId);
172                             }
173                         }
174                     });
175                 }
176             }
177         
178             function nextStep() {
179                 addSelectedGoodsIdToArray();
180                 console.log("ids length"+idsArray.length);
181                 if(idsArray.length>0){
182                     ids = '';
183                     for(var index=0;index<idsArray.length;index++){
184                         ids += idsArray[index];
185                         if(index != idsArray.length-1){
186                             ids += ',';
187                         }
188                     }
189                 }else{
190                     
191                 }
192                 parent.$.modalDialog({
193                     title : '商品排序',
194                     width : 1632,
195                     height : 830,
196                     href : "${pageContext.request.contextPath}/coupons/showAddStep3?goodsId="+ids,
197                     onLoad:function(){
198                         
199                     },
200                     buttons : [ {
201                         text : '下一步',
202                         iconCls : 'icon-ok',
203                         handler : function() {
204                             parent.$.modalDialog.openner= $grid;//因为添加成功之后,需要刷新这个dataGrid,所以先预定义好
205                             var f = parent.$.modalDialog.handler.find("#form");
206                             f.submit();
207                         }
208                     }, {
209                         text : '取消',
210                         iconCls : 'icon-cancel',
211                         handler : function() {
212                             parent.$.modalDialog.handler.dialog('destroy');
213                             parent.$.modalDialog.handler = undefined;
214                         }
215                     }
216                     ]
217                 });
218             }
219             //编辑
220             function editOneGood() {
221                 //console.log("run edit");
222                 var row = $dg.datagrid('getSelected');
223                 if (row) {
224                     window.location.href="${pageContext.request.contextPath}/goods/showEditGoods?goodsId="+row.goodsId;
225                 }else{
226                     parent.$.messager.show({
227                         title :"提示",
228                         msg :"请选择一行记录!",
229                         timeout : 1000 * 2
230                     });
231                 }
232             }
233             function addOneGood() {
234                 //console.log("run edit");
235                 window.location.href="${pageContext.request.contextPath}/goods/showAddGood";
236             }
237             
238             //高级搜索 删除 row
239             function tbCompanySearchRemove(curr) {
240                     $(curr).closest('tr').remove();
241             }
242             //高级查询
243             function tbsCompanySearch() {
244                 jqueryUtil.gradeSearch($dg,"#tbCompanySearchFm","jsp/company/companySearchDlg.jsp");
245             }
246             
247             /**
248              * 格式化日期(含时间)
249              */
250             function formatterDate(date) {
251                 var datetime = date.getFullYear()
252                 + "-"// "年"
253                 + ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0"
254                         + (date.getMonth() + 1))
255                 + "-"// "月"
256                 + (date.getDate() < 10 ? "0" + date.getDate() : date
257                         .getDate())
258                 + " "
259                 + (date.getHours() < 10 ? "0" + date.getHours() : date
260                         .getHours())
261                 + ":"
262                 + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date
263                         .getMinutes())
264                 + ":"
265                 + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date
266                         .getSeconds());
267                 return datetime;
268             }
269             
270             function removeArrayValue(arr, val) {
271               for(var i=0; i<arr.length; i++) {
272                 if(arr[i] == val) {
273                   arr.splice(i, 1);
274                   break;
275                 }
276               }
277             }
278         </script>
279   </head>
280   <body>
281       <div data-options="region:'center',border : false">
282           <div class="well well-small" style="margin-left: 5px;margin-top: 5px">
283             <span class="badge">添加优惠券步骤</span>
284             <p>
285                 1:填写优惠券基本信息&nbsp——————————&nbsp<span class="label-info"><strong>2:选择优惠券中的商品</strong></span>&nbsp——————————&nbsp3:保存并生成优惠券
286             </p>
287         </div>
288         <div id="tb" style="padding:2px 0">
289             <table cellpadding="0" cellspacing="0">
290                 <tr>
291                     <td style="padding-left:2px">
292                             <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="nextStep()">下一步</a>
293                             <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="">取消</a>
294                     </td>
295                     <!-- <td style="padding-left:2px">
296                         <input id="searchbox" type="text"/>
297                     </td> -->
298                     <!--  <td style="padding-left:2px">
299                         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-search" plain="true" onclick="tbsCompanySearch();">高级查询</a>
300                     </td>-->
301                 </tr>
302             </table>
303         </div>
304         <table id="dg" title="添加优惠券步骤2"></table>
305       </div>    
306   </body>
307 </html>

2、页面大概的样子

3、问题及解答,问题层层递进,每一个问题的前提是前一个问题已经解决。

已知:一个普通的datagrid表格。

问题1:如何实现翻页。

          前台:pagination:true,表示显示分页toolbar。

       后台:

 1 @RequestMapping("/getGoodsOnSale")
 2     @ResponseBody
 3     public GridModel getGoodsOnSale(HttpServletRequest request, @RequestParam("page") Integer page,
 4             @RequestParam("rows") Integer rows) {
 5         Integer userRight = (Integer)(LoginController.getFromSession(request, ConstantsUtil.SESSION_USER_RIGHT));
 6         List<Goods> goods = new ArrayList<Goods>();
 7         Long total = new Long(0);
 8         if(userRight.equals(ConstantsUtil.USER_RIGHTS_ADMIN)){
 9             goods = goodsService.getGoodsOnSale(page, rows);
10             total = goodsService.getGoodsOnSaleCount();
11         }else{
12             List<Brand> brands = (List<Brand>)(LoginController.getFromSession(request, ConstantsUtil.SESSION_USER_BRANDS));
13             goods = goodsService.getGoodsOnSale(brands,page, rows);
14             total = goodsService.getGoodsOnSaleCount(brands);
15         }
16         GridModel gridModel = getGoods(goods, request);
17         gridModel.setTotal(total);
18         return gridModel;
19     }

说明:后台从request.getParameter里取两个参数,page和rows,分别代表当前的页数及每页显示几行数据。total是总数据数。

GridModel类:

public class GridModel {
    private List  rows= new ArrayList();
    private Long total=0L;
    public List getRows() {
        return rows;
    }
    public void setRows(List rows) {
        this.rows = rows;
    }
    public Long getTotal() {
        return total;
    }
    public void setTotal(Long total) {
        this.total = total;
    }
}

问题2:如何在datagrid表格里第一列显示checkbox,并且让行选中和checkbox选中等同?

答:

1、singleSelect:false,设置表格为复选模式

2、{field:'ck',checkbox:true},这里面的checkbox:true表示该列显示复选按钮。

2、查看easyUI的文档:http://www.jeasyui.net/plugins/183.html可以得知两个属性——checkOnSelect和selectOnCheck。

checkOnSelect:如果设置为 true,当用户点击某一行时,则会选中/取消选中复选框。如果设置为 false 时,只有当用户点击了复选框时,才会选中/取消选中复选框。

selectOnCheck:如果设置为 true,点击复选框将会选中该行。如果设置为 false,选中该行将不会选中复选框。

所以,将这两个属性置为true。

问题3:如何在执行翻页以前将被选中的行的主键保存起来

答:此问题可分解为以下两个问题:

1、如何将勾选中的行保存起来

因为翻页是重新到后台取下一页数据,也就是数据重新加载的过程,所以可以考虑在onBeforeLoad时做相关处理。

先定义好一个数组idsArray用来保存选中行的主键,再用$dg.datagrid('getSelections')取得选中的行。也就是105行的方法addSelectedGoodsIdToArray做的事情。

下面看上边发的大概样子图片,点击“下一步”是将当前datagrid中被选中的内容提交到后台处理,即页面中的function nextStep()要做的事,所以在netStep()中需要首先执行

一下addSelectedGoodsIdToArray,将选中的内容保存起来,否则当数据提交后台时,当前这一页选中的行并没有存起来,因为当前这一页的addSelectedGoodsIdToArray并未触发执行。

2、如何将选中以后又取消选中的行从保存的记录中删除

经过测试,在我将checkOnSelect和selectOnCheck都设为true以后, onClickRow在被调用时会自动调用onCheck或onUncheck(请注意此处的拼写,后一个check的首字母是小写,如果误

写成大写就会失效),而onCheck和onUncheck在执行时并不会自动调用onClickRow。所以,如果我们想要在用户取消勾选一行以后做点事,只要在onUncheck里做就行了。这就是52行

做的事。

问题4:如何在datagrid数据加载完之后自动将被选中的行选中?

答:因为翻页是重新到后台取下一页数据,也就是数据重新加载的过程。所以只要在onLoadSuccess中解决这个勾选的问题,那么当向前翻页的时候,之前选中的行也会实现自动勾选。

1、onLoadSuccess方法中传进来的data参数,它的data.rows()表示当前datagrid中的数据。

2、$dg.datagrid('selectRow',index);将第index行的数据选中。这里的index从零开始,index不等于当前行的数据的主键,而是表格的自然行号。

3、data.rows().goodsId:取得当前行数据的goodsId属性的值

知道了以上三点,大概就清楚了,遍历idsArray,将当前行的主键与之匹配,匹配上了就勾选。

注意第三点,我们选择一列值的前提是该列被显示在表格中,如果想隐藏它,只需hidden:true。

 

参考文章:http://www.jeasyui.net/plugins/183.html

      http://my.oschina.net/u/1410278/blog/185614

原文地址:https://www.cnblogs.com/mabaishui/p/5757637.html