推扬网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
推扬网 门户 经验分享 查看内容

jQuery EasyUI datagrid在翻页以后仍能记录被选中行的实现代码

2020-4-11 13:57| 发布者: admin| 查看: 324| 评论: 0

这篇文章主要介绍了jQuery EasyUI datagrid在翻页以后仍能记录被选中行的实现代码的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下

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

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>添加优惠券步骤2</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<jsp:include page="../layout/script.jsp"></jsp:include>
<c:set var="getDataUrl" value="${pageContext.request.contextPath}/goods/getGoodsOnSale" scope="request" />
<script type="text/javascript">
var $dg;
var $grid;
var ids = '';
var idsArray = new Array();
$(function() {
$dg = $("#dg");
$grid=$dg.datagrid({
url : "${getDataUrl}",
width : 'auto',
height : $(this).height()-85,
pagination:true,
rownumbers:true,
border:true,
striped:true,
singleSelect:false,
checkOnSelect:true,
selectOnCheck:true,
onBeforeLoad:function(data){
addSelectedGoodsIdToArray();
},
onLoadSuccess:function(data){
var rowsData = data.rows;
if(idsArray.length!=0){
$.each(idsArray,function(i,e){
for(var index=0;index<rowsData.length;index++){
if(rowsData[index].goodsId==e){
$dg.datagrid('selectRow',index);
}
}
});
}
},
onUncheck:function(rowIndex,rowData){
if(idsArray.length == 0){
}else{
for(var index=0;index<idsArray.length;index++){
if(idsArray[index] == rowData.goodsId){
removeArrayValue(idsArray,rowData.goodsId);
break;
}
}
}
},
columns : [ [ {field:'ck',checkbox:true},
{field : 'goodsId',hidden:true},
{field : 'goodsName',title : '商品标题',width : parseInt($(this).width()*0.3)},
{field : 'img1',title : '图片',width : parseInt($(this).width()*0.1),align : 'left',
formatter:function(value,row){
if(row.img1 != '')
return "<img src = '"+row.img1+"'/>";
else
return "<img src = '"+row.img1+"'/>"; 
}
},
{field : 'categoryId',title : '分类',width : parseInt($(this).width()*0.1),align : 'left',
formatter:function(value,row){
var cates = row.categorys;
for(var i=0;i<cates.length;i++){
if(cates[i].categoryId === row.categoryId){
return cates[i].categoryName;
}
} 
}
},
{field : 'goodsNumber',title : '库存',width : parseInt($(this).width()*0.1)},
{field : 'isOnSale',title : '上架',width :parseInt($(this).width()*0.1),align : 'left',
formatter:function(value,row){
if(row.isOnSale){
return "<font color=green>是<font>";
} else{
return "<font color=red>否<font>"; 
}
}
},
{field : 'lastUpdate',title : '上架时间',width : parseInt($(this).width()*0.1),align : 'left',
formatter:function(value,row){
var thisDate = new Date(row.lastUpdate);
return formatterDate(thisDate);
}
}
] ],toolbar:'#tb'
});
//搜索框
/* $("#searchbox").searchbox({ 
menu:"#mm", 
prompt :'模糊查询',
searcher:function(value,name){ 
var str="{\"searchName\":\""+name+"\",\"searchValue\":\""+value+"\"}";
var obj = eval('('+str+')');
$dg.datagrid('reload',obj); 
}
}); */
});
function addCheckedGoodIdToArray(rowIndex,rowData){
console.log("_________________________");
var idsArrayLength = idsArray.length;
if(idsArray.length == 0){
console.log("push:"+rowData.goodsId);
idsArray.push(rowData.goodsId);
}else{
for(var index=0;index<idsArrayLength;index++){
if(idsArray[index] == rowData.goodsId){
console.log("remove:"+rowData.goodsId);
removeArrayValue(idsArray,rowData.goodsId);
break;
}
if(index == idsArrayLength-1){
console.log("push:"+rowData.goodsId);
idsArray.push(rowData.goodsId);
}
}
}
console.log("---------------");
for(var index=0;index<idsArray.length;index++){
console.log(idsArray[index]);
}
console.log("---------------");
}
function addSelectedGoodsIdToArray(){
var rows = $dg.datagrid('getSelections');
if(rows.length>0){
$.each(rows,function(i,row){
if(idsArray.length == 0){
idsArray.push(row.goodsId);
}else{
for(var index=0;index<idsArray.length;index++){
if(idsArray[index] == row.goodsId){
break;
}
if(index == idsArray.length-1){
idsArray.push(row.goodsId);
break;
}
}
}
});
}
}
function removeSelectedGoodsIdToArray(rows){
//var rows = $dg.datagrid('getSelections');
if(rows.length>0){
$.each(rows,function(i,row){
if(idsArray.length > 0){
for(var index=0;index<idsArray.length;index++){
removeArrayValue(idsArray,row.goodsId);
}
}
});
}
}
function nextStep() {
addSelectedGoodsIdToArray();
console.log("ids length"+idsArray.length);
if(idsArray.length>0){
ids = '';
for(var index=0;index<idsArray.length;index++){
ids += idsArray[index];
if(index != idsArray.length-1){
ids += ',';
}
}
}else{
}
parent.$.modalDialog({
title : '商品排序',
width : 1632,
height : 830,
href : "${pageContext.request.contextPath}/coupons/showAddStep3?goodsId="+ids,
onLoad:function(){
},
buttons : [ {
text : '下一步',
iconCls : 'icon-ok',
handler : function() {
parent.$.modalDialog.openner= $grid;//因为添加成功之后,需要刷新这个dataGrid,所以先预定义好
var f = parent.$.modalDialog.handler.find("#form");
f.submit();
}
}, {
text : '取消',
iconCls : 'icon-cancel',
handler : function() {
parent.$.modalDialog.handler.dialog('destroy');
parent.$.modalDialog.handler = undefined;
}
}
]
});
}
//编辑
function editOneGood() {
//console.log("run edit");
var row = $dg.datagrid('getSelected');
if (row) {
window.location.href="${pageContext.request.contextPath}/goods/showEditGoods?goodsId="+row.goodsId;
}else{
parent.$.messager.show({
title :"提示",
msg :"请选择一行记录!",
timeout : 1000 * 2
});
}
}
function addOneGood() {
//console.log("run edit");
window.location.href="${pageContext.request.contextPath}/goods/showAddGood";
}
//高级搜索 删除 row
function tbCompanySearchRemove(curr) {
$(curr).closest('tr').remove();
}
//高级查询
function tbsCompanySearch() {
jqueryUtil.gradeSearch($dg,"#tbCompanySearchFm","jsp/company/companySearchDlg.jsp");
}
/**
* 格式化日期(含时间)
*/
function formatterDate(date) {
var datetime = date.getFullYear()
+ "-"// "年"
+ ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0"
+ (date.getMonth() + 1))
+ "-"// "月"
+ (date.getDate() < 10 ? "0" + date.getDate() : date
.getDate())
+ " "
+ (date.getHours() < 10 ? "0" + date.getHours() : date
.getHours())
+ ":"
+ (date.getMinutes() < 10 ? "0" + date.getMinutes() : date
.getMinutes())
+ ":"
+ (date.getSeconds() < 10 ? "0" + date.getSeconds() : date
.getSeconds());
return datetime;
}
function removeArrayValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}
</script>
</head>
<body>
<div data-options="region:'center',border : false">
<div class="well well-small" style="margin-left: 5px;margin-top: 5px">
<span class="badge">添加优惠券步骤</span>
<p>
1:填写优惠券基本信息 —————————— <span class="label-info"><strong>2:选择优惠券中的商品</strong></span> —————————— 3:保存并生成优惠券
</p>
</div>
<div id="tb" style="padding:2px 0">
<table cellpadding="0" cellspacing="0">
<tr>
<td style="padding-left:2px">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="nextStep()">下一步</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="">取消</a>
</td>
<!-- <td style="padding-left:2px">
<input id="searchbox" type="text"/>
</td> -->
<!-- <td style="padding-left:2px">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-search" plain="true" onclick="tbsCompanySearch();">高级查询</a>
</td>-->
</tr>
</table>
</div>
<table id="dg" title="添加优惠券步骤2"></table>
</div> 
</body>
</html>

2、页面大概的样子

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

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

问题1:如何实现翻页。

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

后台:

@RequestMapping("/getGoodsOnSale")
@ResponseBody
public GridModel getGoodsOnSale(HttpServletRequest request, @RequestParam("page") Integer page,
@RequestParam("rows") Integer rows) {
Integer userRight = (Integer)(LoginController.getFromSession(request, ConstantsUtil.SESSION_USER_RIGHT));
List<Goods> goods = new ArrayList<Goods>();
Long total = new Long();
if(userRight.equals(ConstantsUtil.USER_RIGHTS_ADMIN)){
goods = goodsService.getGoodsOnSale(page, rows);
total = goodsService.getGoodsOnSaleCount();
}else{
List<Brand> brands = (List<Brand>)(LoginController.getFromSession(request, ConstantsUtil.SESSION_USER_BRANDS));
goods = goodsService.getGoodsOnSale(brands,page, rows);
total = goodsService.getGoodsOnSaleCount(brands);
}
GridModel gridModel = getGoods(goods, request);
gridModel.setTotal(total);
return gridModel;
}

说明:后台从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。

以上所述是小编给大家介绍的jQuery EasyUI datagrid在翻页以后仍能记录被选中行的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对推扬网www.tuiyang.com网站的支持!


鲜花

握手

雷人

路过

鸡蛋

最新评论

精选推荐

    广告服务|投稿要求|禁言标准|版权说明|免责声明|手机版|小黑屋|推扬网 ( 粤ICP备18134897号 )|网站地图 | 邮箱:vayae@hotmail.com

    GMT+8, 2024-3-29 07:14 , Processed in 0.347594 second(s), 28 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    返回顶部