jqGrid笔记_unity完全自学手册

(5) 2024-05-24 17:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说jqGrid笔记_unity完全自学手册,希望能够帮助你!!!。

jqGrid笔记
api网站链接:https://blog.mn886.net/jqGrid/
1. get
1.1 获取所有数据

$("#jqGrid").getRowData();

1.2 获取所有id

var ids = $('#jqGrid').getDataIDs();

1.3 获取第一行

var rowData = $("#jqGrid").getRowData(ids[0]);

1.4 获取指定行

var rowData = $("#jqGrid").jqGrid('getRowData',id);

1.5 获取选中行数据

var id = $("#jqGrid").jqGrid("getGridParam", "selrow");  
var rowData = $('#jqGrid').jqGrid('getRowData',id);
rowData.status;  //获取指定字段

2. 查询

$("#jqGrid").jqGrid({
	url : '${ctx}/queryTableList',
	postData : {
		idpath : idpath
	},
	mtype : "POST",
	styleUI : 'Bootstrap',
	datatype : "json",
	cache : false,
	colModel : 
		[ 
		  {label : '',name : 'id',hidden : true},
          {label : '收入方',name : 'corgname',width : 150,formatter:function(cellvalue){return "";}}
	    ],
	rownumbers:true, //true 显示行号
	multiselect : false,
	viewrecords : true,//是否显示行数 
	height : "auto",
	autowidth : true,
	shrinkToFit : true,
	rowNum : 10,
	autoScroll : false,
	rowList : [ 10, 20, 30 ],//可调整每页显示的记录数 
	pager : "#jqGridPager", //分页工具栏  
	pagerpos : 'left'
});

3. 嵌套子表格

function queryTable() {
	$("#jqGrid").jqGrid({
		url : '${ctx}/income',
		postData : {
			startDate : start,
			endDate : end
		},
		mtype : "POST",//ajax的提交方式,默认是get
		styleUI : 'Bootstrap',
		datatype : "json",//服务端返回的类型
		cache : false,
		colModel : 
			[ 
			  {label : '',name : 'id',hidden : true},
              {label : '收入方',name : 'orgname',width : 150}
		    ],
		multiselect : false,
		subGrid : true,//开启子表格支持
		subGridRowExpanded : function(subgrid_id, row_id) {
			//子表格容器的id和需要展开子表格的行id
			openSubGrid(subgrid_id, row_id);
		},
		viewrecords : true,//是否显示行数 
		height : "auto",
		beforeRequest : function() {
			$.ajax({
				url : "${ctx}/dictionary/paymentMethod",
				type : "get",
				data : {
				},
				async : false,
				dataType : "json",
				success : function(data) {
					console.log(data);
				},
				error : function(data) {
				}
			});
		},
		autowidth : false,
		shrinkToFit : true,
		rowNum : 10,
		autoScroll : false,
		rowList : [ 10, 20, 30 ],//可调整每页显示的记录数 
		pager : "#jqGridPager", //分页工具栏  
		pagerpos : 'left'
	});
}

function openSubGrid(subgrid_id, rowid) {//开启子表格
	var subgrid_table_id = subgrid_id + "_t";//获取子表格的id
	var subgrid_paper_id = subgrid_id + "_pgr";//获取子表格的paper的id
	//动态添加子报表的id和paper
	$("#" + subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll' >");
	$("#" + subgrid_table_id).jqGrid({
		url : '${ctx}/incomeDetail',
		postData : {
			id : rowid
		},
		mtype : "POST",
		styleUI : 'Bootstrap',
		datatype : "json",
		cache : false,
		colModel : 
			[ 
	            {label : '',name : 'id',hidden : true}, 
				{label : '名称',name : 'name',width : 100,sortable : false}, 
				{label : '单价',name : 'price',width : 100,sortable : false,formatter:function(cellvalue){return "";}}
			],
		multiselect : false,
		viewrecords : true, 	//是否显示行数 
		height : "auto",
		autowidth : false,
		shrinkToFit : true,
		rowNum : 10,
		autoScroll : false,
		rowList : [ 10, 20, 30 ],//可调整每页显示的记录数 
		pagerpos : 'left'
	});
}

4. 重新加载
4.1 带参数

$("#jqGrid").jqGrid('setGridParam',{    
    datatype:'json',    //返回的数据类型
    postData:{			//请求的参数
	    startDate:start,
	    endDate:end
    },  
    page:1    			//请求的页数
}).trigger("reloadGrid");  

4.2 不带参数的简写

$("#jqGrid").trigger("reloadGrid");

5. 事件
5.1 选中行onSelectRow

onSelectRow: function(id,status){
}

5.2 加载完成loadComplete

loadComplete:function(data){
	// 设置第一行选中
	var ids = $('#jqGrid').getDataIDs();
    $("#jqGrid").jqGrid('setSelection',ids[0]);
}

6. 多级表头
6.1 设置二级表头
CSS

<style>
.red{
	color: #ff0000b5
}

.green{
	color: green
}

.disabled{
  background-color: #eee;
  cursor: not-allowed
}

.open{
  background-color: #7FFF00;
  cursor: pointer
}

.close{
  background-color: #FFFF00;
  cursor: pointer
}

.clicked{
	background-color: green;
}

#todaySche {
	width: 560px;
	display: none;
	pointer-events: none;
	position: absolute;
	font-size: 14px;
	overflow: auto;
	height: 17rem;
	z-index: 999;
	background-color: rgba(211, 211, 211, 0.7);
}

#gbox_table{
	overflow: auto;
	height: 95%;
}

#gbox_table th{
	text-align: center;
}
</style>

页面

<div id="tableDiv">
    <table id="table"></table>
	<div id="todaySche"></div>
</div>

JS

<script type="text/javascript">
	function loadData(year,month,date) {
		var twoWeek = twoWeekCalender(year,month,date);
	    
		$.jgrid.defaults.responsive = true;
		$.jgrid.defaults.styleUI = 'Bootstrap';
		$.jgrid.defaults.loadtext = "<h2>读取中...</h2>";
		
		var colNames = [ 'id', '日期' ];
		var getGroupHeaders = [];
		var JqGridColModel = [ 
			{
				name : 'id',
				hidden : true,
			}, 
			{
				name : 'testName',
				width : 100,
				align : 'center',
				sorttype : 'string',
				sortable : false
			} 
		]; 
		
		for (var i = 0; i < twoWeek.length; i++) {
			var md = twoWeek[i].md;
			colNames.push(twoWeek[i].week);
		
			JqGridColModel.push({
				name: md,
				index: i+1,
				ymd: twoWeek[i].ymd,
				y: twoWeek[i].y,
				m: twoWeek[i].m,
				d: twoWeek[i].d,
				width: 50,
				align: 'center',
				sorttype: 'string',
				sortable: false,
				cellattr: fullColor,
				formatter: cellFormatter
			});
			getGroupHeaders.push({startColumnName: md,numberOfColumns: 1,titleText: md});
		}
		
		$("#table").jqGrid({
			url : "${ctx}/gridList",
			postData : {
				firstDate : firstDate,
				lastDate : lastDate,
				orgId : orgId
			},
			mtype : "post",
			datatype : "json",
			colNames : colNames,
			colModel : JqGridColModel,
			viewrecords : true,//是否要显示总记录数
			height : $(window).height() * 0.7,
			autowidth : true,
			shrinkToFit : true,//如果为ture,则按比例初始化列宽度。如果为false,则列宽度使用colModel指定的宽度
			beforeSelectRow: function (rowid, e) {
				//禁用表格点击选中
			    var $myGrid = $(this), 
		        i = $.jgrid.getCellIndex($(e.target).closest('td')[0]), 
		        cm = $myGrid.jqGrid('getGridParam', 'colModel'); 
			    return (cm[i].name === 'cb'); 
			}
		});
		//设置二级表头
		$("#table").jqGrid('setGroupHeaders', {
			useColSpanStyle : true,
			groupHeaders : getGroupHeaders
		}); 
	}
	/**
	 * 刷新表格
	 */
    function tabRefresh() {
		$("#gbox_table").remove(); // 先移除jqgrid表格
		$("#tableDiv").append('<table id="table"></table>');//再加一个空表格
		loadData(year,month,date);
	}

	/**
	 * 改变单元格背景色
	 */
	function fullColor(rowId, val, rowObject, cm, rdata) {
		var cls = $(val).attr("cls");
		var past = $(val).attr("past");//过去的时间
		var equipId = $(val).attr("equipId");
		var day = $(val).attr("day");
		var index = $(val).attr("index");
		
		if(cls == 'disabled' && past != 'past'){
			return "style='background-color: #eee;cursor: not-allowed'";
		}else if(cls == 'open'){
			return "style='background-color: #7FFF00;cursor: pointer' onmouseover='scheByDay("+ equipId + "," + day + "," + index + ")'; onmouseout='hide()' ";
		}else if(cls == 'close'){
			return "style='background-color: #FFFF00;cursor: pointer' onmouseover='scheByDay("+ equipId + "," + day + "," + index + ")'; onmouseout='hide()' ";
		}
		if(past == 'past'){
			//过去的时间也展示
			return "style='background-color: #eee' onmouseover='scheByDay("+ equipId + "," + day + "," + index + ")'; onmouseout='hide()' ";
		}
	}
	/**
	 * 小于今天的列置灰
	 */
	function cellFormatter(cellvalue, options, rowObject){
		var html = "";
		var coordinate = rowObject.id+"_"+options.colModel.ymd;	//坐标
		var index = options.colModel.index;
		var ymd = options.colModel.ymd;
		var curr = new Date(options.colModel.y,options.colModel.m-1,options.colModel.d); 
		var now = new Date();//今天
		now = new Date(now.getFullYear(),now.getMonth(),now.getDate());
		cellvalue = rowObject[options.colModel.ymd];
		if(curr < now){//小于今天
			if(cellvalue){
				html += "<div id='div_"+coordinate+"' cls='disabled' past='past' equipId='"+rowObject.id+"' day='"+ymd+"' index='"+index+"'>"+v+"</div>";
			}else{
				html += "<div id='div_"+coordinate+"' cls='disabled'><i class='fa fa-minus fa-lg red'></i></div>";
			}
		}else{//大于等于今天
			if(cellvalue){
				var v = "";
				if(cellvalue.isOpen == 1){//开放
					html += "<div id='div_"+coordinate+"' onclick=changeBackgroundColor(this) class='unchecked' equipId='"+rowObject.id+"' day='"+ymd+"' index='"+index+"' cls='open' style='display:list-item;'>"+v+"</div>";
				}else{//不开放
					html += "<div id='div_"+coordinate+"' onclick=changeBackgroundColor(this) class='unchecked' equipId='"+rowObject.id+"' day='"+ymd+"' index='"+index+"' cls='close' style='display:list-item;'>"+v+"</div>";
				}
				html += "<input style='width:0;height:0' type='checkbox' name='chkUpdate' value='"+coordinate+"' />";
			}else{
				html += "<div id='div_"+coordinate+"' onclick=changeIcon(this) class='unchecked' style='display:list-item;'><i class='fa fa-minus fa-lg red'></i></div>";
				html += "<input style='width:0;height:0' type='checkbox' name='chk' value='"+coordinate+"' />";
			}
		}
		return html;
	}

	function changeIcon(e){
		if(e.className == "unchecked"){
			e.className = "checked";
			e.innerHTML = "<i class='fa fa-check fa-lg green'></i>";
			e.nextSibling.checked = true;
		}else{
			e.className = "unchecked";
			e.innerHTML = "<i class='fa fa-minus fa-lg red'></i>";
			e.nextSibling.checked = false;
		}
	}

	function changeBackgroundColor(e){
		if(e.className == "unchecked"){
			$(e).parent().css("background",'#87CEFA');
			e.className = "checked";
			e.nextSibling.checked = true;
		}else{
			var cls = $(e).attr('cls');
			if(cls == 'open'){
				$(e).parent().css("background",'#7FFF00');
			}else if(cls == 'close'){
				$(e).parent().css("background",'#FFFF00');
			}
			e.className = "unchecked";
			e.nextSibling.checked = false;
		}
	}

	/**
	 * 点击某个单元格,悬浮显示今日详情
	 * @param id
	 * @param day
	 */
	function scheByDay(id, ymd ,index) {
		// 跟随鼠标移动事件
		var oEvent = event;
		var oDiv = document.getElementById('richeng');
		var scrollTop = document.documentElement.scrollTop
				|| document.body.scrollTop;
		var scrollLeft = document.documentElement.scrollLeft
				|| document.body.scrollLeft;
		
		var iRow = $('#' + id)[0].rowIndex; // 根据id获取行号
		var rowData = $("#table").jqGrid("getRowData", id);
		var list = '';
		style = "visibility: none;";
		$.ajax({
			url : '${ctx}/scheByDay',
			type : "post",
			data : {
				date : ymd,
				equipId : id
			},
			dataType : "json",
			async : false,
			success : function(data) {
				list = data;
			},
			error : function(data) {
			}
		});

		var html = "";
		if (list.length > 0) {
			html += "<table><tr><td colspan='5' align='center'>"+ymd+"排班</td></tr><tr><td style='width:100px' align='center'>时间段</td><td style='width:100px' align='center'>已预约次数</td>";
			html += "<td style='width:120px'; align='center' >可预约次数</td><td style='width:120px' align='center'>可预约总次数 </td><td style='width:120px' align='center'>开放状态</td></tr>";
			for (var i = 0; i < list.length; i++) {
				html += "<tr><td align='center'>"+list[i].start + "-" + list[i].end+"</td> <td align='center'>"+list[i].used+"</td> ";
				html += "<td align='center'>" + (list[i].total - list[i].used) + "</td> <td align='center'>"+list[i].total+"</td><td align='center'>" + openStr + "</td></tr>";
			}
			html += "</table>";
		} else {
			html += '暂无排班信息';
		}

		// 在最右边的时候 改变悬浮的位置
		if (index >= 8) {
			oDiv.style.left = oEvent.clientX - 750 +  'px';
		} else {
			oDiv.style.left = oEvent.clientX - 200 + 'px';
		}

		// 在最下面的时候 改变悬浮的位置
		if (iRow >= 24) {
			oDiv.style.top = oEvent.clientY + scrollTop - 200 + 'px';
		} else {
			oDiv.style.top = oEvent.clientY + scrollTop + 'px';
		}
		
		// 事件太多改变宽度
		if (list.length >= 4) {
			oDiv.style.height = (15 + list.length) + 'rem';
		} else {
			oDiv.style.height = '';
		}
		$("#todaySche").empty().append(html);
		$("#todaySche").show();
	}
	
	function hide() {
		$("#todaySche").hide();
	}
</script>

6.2 多级表头时,设置表头宽度

$('#gbox_table').find('th:eq(1)').each(function() {
	$(this).css('width', "40px");
});

$('#table tr').find('td:eq(1)').each(function() {
	$(this).css('width', "40px");
}) 

7. 其他
7.1 jqGrid单元格内容自动换行

1、设置样式
 .colCss{
	  white-space: normal !important; 
	  height:auto;
  }
2、给列加个属性classes,使classes=‘colCss’

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复