jqGrid subgrid 使用指南:参数、方法、事件说明及一个完整的DEMO演示

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chuangxin/article/details/90255867

jQuery DataTable有类似subgrid功能,实现也比较简单,只要设置列class “details-control”,并绑定td.details-control的click事件,在事件中实现对应行row.child(subgrid内容).show() 或 hide()即可。jqGrid同样提供了subgrid功能,而且实现更加简单。

一、jqGrid 用户参考手册 关于subgrid说明

jqGrid subgrid 官方使用说明:http://www.guriddo.net/documentation/guriddo/javascript/user-guide/subgrid/

关键参数说明:

Property Type Description Default
subGrid boolean If set to true this enables using a subGrid. If the subGrid is enabled additional column at left side is added to the basic grid. This column contains a ‘plus’ icon, which indicate that the user can click on it to expand the row. By default all rows are collapsed. false
subGridOptions object A set of options for the subGrid. Below are all the options with their default values {
plusicon : classes.icon_plus,
minusicon : classes.icon_minus,
openicon: “ui-icon-carat-1-sw”,
expandOnLoad: false,
selectOnExpand : false,
selectOnCollapse:false,
reloadOnExpand : true
}
plusicon and minusicon defies the icons when the grid is collapsed/expanded. The icons are defined in the styleUI object for the particular CSS - see subGrid property.
openicon the icon bellow the minusicon when the subGrid row is expanded - see the same property from subGrid property.
expandOnLoad when set to true make it so that all rows will be expanded automatically when a new set of data is loaded.
selectOnLoad when set to true the row is selected when a plusicon is clicked with the mouse.
selectOnCollapse when set to true the row is selected when a minusicon is clicked with the mouse.
reloadOnExpand If set to false the data in the subGrid is loaded only once and all other subsequent clicks just hide or show the data and no more ajax calls are made.
subGridModel array This property, which describes the model of the subGrid, has an effect only if the subGrid property is set to true. It is an array in which we describe the column model for the subGrid data. The syntax is :
subGridModel : [
{
name: [‘name_1’, ‘name_2’, …, ‘name_n’],
width: [width_1, width_2, …, width_n],
align: [‘left’, ‘center’, …, ‘right’],
params: [param_1, …, param_n],
mapping: [‘name_1_map’, ‘name_2_map’, …, ‘name_n_map’]
}
Where
name: an array containing the labels of the columns of the subGrid.
width: an array containing the width of the columns. This array should have the same length as in name array.
align: an array containing the alignment of the columns. The values can be left, center or right. If omited the alignment is left.
params: an array in which we can add a name from main grid’s colModel to pass as additional parameter to the subGridUrl when click on the plus icon.
mapping: the parameter is used only when repeatitems in subGrid is set to false. When defined in this case we use the names from this array to map it to the subGrid names. If not set and repeatitems is false we use the name option.
subgridtype mixed This option allow loading subGrid as a service. If not set, the datatype parameter of the parent grid is used. See the example below null
subGridWidth integer Determines the width of the subGrid column if subGrid is enabled. 20

subgrid 常用的事件:

  • 事件参数通用说明:
    pID为subgrid所在父容器div的id(如:表格ID为orders, rowid=“3”, 则pID=“orders_3”),id为行rowId;
  • subGridBeforeExpand( pID, id),jqGridSubGridBeforeExpand(event pID, id)
    点击+按钮触发,返回true|false, 返回false则行不会展开,subgrid不会打开。
  • subGridRowExpanded( pID, id),jqGridSubGridRowExpanded(event pID, id)
    展开subgrid时触发
  • subGridRowColapsed( pID, id),jqGridSubGridRowExpanded(event pID, id)
    收起subgrid时触发
  • isHasSubGrid( row_id )
    看起来更像是一个判断表格行是否显示"+“图标回调函数。
    返回true则显示,返回false则不显示”+"图标(该行没有subgrid)。

subgrid 常用的3个方法:

  • 展开subgrid,expandSubGridRow( row_id )
  • 收起subgrid,collapseSubGridRow( row_id )
  • toggleSubGridRow,toggleSubGridRow( row_id )

2、一个完整的DEMO演示

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>jggrid-subgrid</title>
	
	<link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
	<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css" />
	<link rel="stylesheet" href="https://cdn.bootcss.com/jqueryui/1.11.0/jquery-ui.min.css" />
	<link rel="stylesheet" href="https://js.cybozu.cn/jqgrid/v5.3.1/css/ui.jqgrid.css" />
	<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
	<script src="https://js.cybozu.cn/jqgrid/v5.3.1/js/jquery.jqGrid.min.js"></script>
	<script src="https://js.cybozu.cn/jqgrid/v5.3.1/js/i18n/grid.locale-en.js"></script>
	<style>
		tr.ui-state-highlight td, tr.selected-row td{background: #dff0d8;}
	</style>
</head>
<body>
<div class="page-content container">
	<div class="page-head" style="padding: 15px 0"> <!-- page-head -->
		<button type="button" class="btn btn-sm" onclick="doExpand()">展开第3行</button>
		<button type="button" class="btn btn-sm" onclick="doCollapse()">收起第3行</button>
	</div><!-- page-head -->
	<div class="page-body"> <!-- page-body -->
		<div class="panel panel-default" id="panel-orders">
			<table id="orders" class="table-bordered"></table>
		</div>
	</div>
</div>
   
<script type="text/javascript">
	var data = [], rowIds = [];
	function getBills() {
		var rowCount = 20;
		for (var i = 0; i < rowCount; i ++) {
			data.push({
				sid: i,
				bill_id: i,
				bill_detail: i,
				goods_id: i,
				unit_id: i,
				package_id: i,
				ref_detail: i,
				goods_no: i + 1,
				goods_name: '零件名称' + rowCount + i,
				car_type_name: '车型' + rowCount + i,
				package_name: '包装器具' + rowCount + i,
				unit: i%2==0 ? '件' : '箱',
				snp: 0.89,
				box_count: rowCount + i,
				total_count: rowCount + i,
				goods_count: rowCount + i,
				out_count: rowCount + i,
				bill_no: 'BN0000000' + i,
			})
		}
		$("#orders").jqGrid("clearGridData").jqGrid('setGridParam',{data: data || []}).trigger('reloadGrid');
	}
	function doExpand() {
		$("#orders").jqGrid("expandSubGridRow", "3");
	}
	function doCollapse() {
		$("#orders").jqGrid("collapseSubGridRow", "3");
	}
	function showSubGrid(pID, pRowId) {
        var html = '<table id="{id}" class="table table-hover"></table>';
        $('#' + pID).append(html.replace("{id}", pID + "_table"));
        var $subgrid = $("#" + pID + "_table");
        $subgrid.jqGrid({
            colModel: [
             	{ label: '供应商', name: 'supplier_name', width: 80 },
             	{ label: '采购时间', name: 'pur_time', width: 80 },
            ],
            datatype: 'local',
            height: 100,
        });
		var rows = [{supplier_name: "supplier: " + pRowId, pur_time: '2019-05-19'}];
		$subgrid.jqGrid("clearGridData").jqGrid('setGridParam',{data: rows}).trigger('reloadGrid');
    }
	
	$(function() {
		$("#orders").jqGrid({
			colModel: [
				{label: "零件号", name: "goods_no", width: 60},
				{label: "零件名称", name: "goods_name", width: 180},
				{label: "车型", name: "car_type_name", width: 70},
				{label: "包装器具", name: "package_name", width: 70},
				{label: "单位", name: "unit", width: 60 },
				{label: "装箱率", name: "snp", width: 50, sorttype: "number"},
				{label: "箱数", name: "box_count", width: 40, sorttype: "number"},
				{label: "需求总数", name: "total_count", width: 70, sorttype: "number"},
				{label: "需求数量", name: "goods_count", width: 70,},
				{label: "出库数量", name: "out_count", width: 70, sorttype: "number"},
				{label: "订单号", name: "bill_no", width: 120},
			],
			datatype: 'local',
			rownumbers: true,
			height: 300,
			rowNum: 1000,
			multiselect: true,
            subGrid: true,
            isHasSubGrid: function(rowId) {
            	return rowId != "2";	// 第2行 + 按钮不会出现
            },
            subGridBeforeExpand: function( pID, id) {
            	return id != "1";	// 第1行不能展开
            },
            subGridRowExpanded: showSubGrid,
            subGridOptions : {
                reloadOnExpand :false,
                selectOnExpand : true 
            },
		});
		getBills();
	});
</script>
</body>
</html>
展开阅读全文

一个完整jqGrid例子。

07-18

[size=12px][/size]rn环境:Eclipse+Tomcat+servlet+jsprn首先新建一个Dynamic Web Project项目rnweb.xml配置如下:rnrnrn rn DataServletrn com.taiji.jqGrid.DataServletrn rn rn DataServletrn /DataServletrn rnrnzjsp.jsp编写如下:rn<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>rnrnrnrn 第一个jqGrid!rnrn rn rn rn rn rn rn rn rnrn rn rnrnrnrn rn rn rn rn rn rn rn rnrnrnrn然后是后台java文件:rnpublic class DataServlet extends HttpServlet rnrn /**rn * rn */rn private static final long serialVersionUID = 1L;rnrn public void doGet(HttpServletRequest request,rn HttpServletResponse response) throws IOException, ServletException rn rn String page="1";rn String rows="1";rn page=request.getParameter("page");rn rows=request.getParameter("rows");rn if(page==null)rn page="1";rn rn if(rows==null)rn rows="2";rn rn System.out.println("page: "+page+" rows: "+rows);rn int totalRecord = 12; // 总记录数(应根据数据库取得,在此只是模拟)rn int totalPage = totalRecord % Integer.parseInt(rows) == 0 ? totalRecordrn / Integer.parseInt(rows) : totalRecord / Integer.parseInt(rows)rn + 1; // 计算总页数rn try rn int index = (Integer.parseInt(page) - 1) * Integer.parseInt(rows); // 开始记录数0rn int pageSize = Integer.parseInt(rows);//2rn // 以下模拟构造JSON数据对象 ,该对象是jqgrid的默认返回对象rn String json = "total: " + totalPage + ", page: " + pagern + ", records: " + totalRecord + ", rows: [";rn for (int i = index; i < pageSize + index && i < totalRecord; i++) rn json += "'id':'" + i + "','invdate':'" + i + "','name':'" + irn + "','amount':'" + i + "','tax':'" + i + "','total':'" + irn + "','note':'" + i + "'";rn if (i != pageSize + index - 1 && i != totalRecord - 1) rn json += ",";rn rn rn json += "]";rn System.out.println(json);rn response.getWriter().write(json); // 将JSON数据返回页面rn catch (Exception ex) rn rn rn rn地址访问jsp的时候,去调用jsp页面的js.js请求地址/DataServlet。通过web.xml配置会找到相应的类,做数据的处理。然后把处理的结果以json的形式返回到页面。 论坛

没有更多推荐了,返回首页