js动态创建DataGrid

和上一篇一样,使用JS动态的创建datagrid也是一件非常简单的事情,以项目中的实例来做说明,当然easyui的官网文档也有,例子很简单:

①从后台获取数据

②根据需要显示数据

③根据需要对显示的数据做样式

④对显示的数据做合计

核心代码:

  • url:getRootPath()+"/labour/contentDetail.do?headid="+ headid,从后台获取数据;
<span style="font-size:18px;">public String queryContentDetailByHeaderid(HttpServletRequest request) throws Exception {
		String headid=CommonUtil.toEmpty(request.getParameter("headid"));
		List<JobContentDetail> jobContentDetailList=null;

		JSONObject data = new JSONObject();
		String json = "";
		try {
			jobContentDetailList = labourservice.queryJobcontentMessageByheadid(headid);
			if(jobContentDetailList != null)
			{
				if(!jobContentDetailList.isEmpty()){
					data.put("rows", JSONArray.fromObject(jobContentDetailList).toString());
					//调用求和
					json = sumPrice(headid,jobContentDetailList);
				}
				data.put("total", jobContentDetailList.get(0));
				data.put("footer", json);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("query error,detail:" +e.getMessage());
		}
		return data.toString();
	}</span>
  • columns:对后台数据做显示;
<span style="font-size:18px;">columns:[[
	{field:'jobcontentmainid',title:'jobcontentmainid',hidden:true},
	{field:'productid',title:'productid',hidden:true},
	{field:'id',title:'id',hidden:true},
	{field:'subcontractorlabour',title:'subcontractorlabour',hidden:true},
	{field:'ck',checkbox:true},
	{field:'opt',title:'opt',width:20,align:'center',
		formatter:function(value,row,index){
			if (row.manuallykeyed == "1") {
				return "<img src=\""+ getRootPath() +"/component/jquery-easyui/themes/icons/edit_remove.png\" onClick=\"del(this)\"/>";
			}
		}},
	{field:'productname',title:'<spring:message code="syspages.workjob.labour.Product"/>',width:250,align:'left'},
	{field:'productusage',title:'<spring:message code="syspages.workjob.labour.ProductUsage"/>',width:100,align:'center'},
	{field:'itemqty',title:'<spring:message code="syspages.workjob.labour.LabourQty"/>',width:60,align:'center',
		styler: function(index,row){
			if (row.itemqty==0){
				return 'background-color:#FFCCCC;';}
		}},
	{field:'buildlabourqty',title:'<spring:message code="syspages.workjob.labour.BuildQty"/>',width:60,align:'center',editor:{type:'numberbox'},
		styler:function(index,row){
			var s1="";
			if (row.id!="footer" && row.builderqty==0){
				s1= 'background-color:#FFCCCC;';
			}
			if(row.id!="footer"){return s1 + s2;}
		}},
	{field:'labourunitname',title:'<spring:message code="syspages.workjob.labour.LabourUnit"/>',width:80,align:'center'},
	{field:'labourfactor',title:'<spring:message code="syspages.workjob.labour.LabourFactor"/>',width:80,align:'center',editor:{type:'numberbox',options:{precision:2}},
		styler: function(index,row){
			var s1="";
			if (row.labourfactor==0){
				s1 = 'background-color:#FFCCCC;';
			}
			if(row.id!="footer"){
				return s1 + 'border-color:rgb(149,184,231);border-style:solid solid solid solid;border-width: 1px;height:30px;'
			};
		}},
	{field:'labourfactor2',title:'<spring:message code="syspages.workjob.labour.LabourFactor"/>',width:80,align:'center',hidden:true,editor:{type:'numberbox',options:{precision:2}},
		styler: function(index,row){
			var s1="";
			if (row.labourfactor2==0){
				s1 =  'background-color:#FFCCCC;';
			}
			if(row.id!="footer"){
				return s1 + 'border-color:rgb(149,184,231);border-style:solid solid solid solid;border-width: 1px;height:30px;'
			};
		}},
	{field:'labourfactor3',title:'<spring:message code="syspages.workjob.labour.LabourFactor"/>',width:80,align:'center',hidden:true,editor:{type:'numberbox',options:{precision:2}},
		styler: function(index,row){
			var s1="";
			if (row.labourfactor3==0){
				s1 = 'background-color:#FFCCCC;';
			}
			if(row.id!="footer"){
				return s1 + 'border-color:rgb(149,184,231);border-style:solid solid solid solid;border-width: 1px;height:30px;'
			};
		}},
	{field:'levelofdifficulty',title:'<spring:message code="syspages.workjob.labour.DegreeofDifficulty"/>',width:80,align:'center',
		editor:{
			type:'combobox',
			options:{
				data:levelPercentData,
				valueField: 'id',
				textField: 'text',
				panelHeight:'300px',
				required: true ,
				editable:false
			}
		},
		styler:function(index,row){
			if(row.id!="footer"){
				return 'border-color:rgb(149,184,231);border-style:solid solid solid none;border-width: 1px;height:30px;'
			};
		},
		formatter:function(value,row,index){
		if(row.id == "footer"){
			return " ";
		}
		else{
			row.levelofdifficulty = value;
			for(var i=0; i<levelPercentData.length; i++){
				if (levelPercentData[i].id == value){
					return levelPercentData[i].text;
				}
			}
			return value;
		}
		}},
	{field:'manhours',title:'<spring:message code="syspages.workjob.labour.ManHours"/>',width:60,align:'center',
		styler: function(index,row){
			if (row.id != "footer" && row.manhours==0){
				return 'background-color:#FFCCCC;';
			}
		}},
	{field:'labourrate',title:'<spring:message code="syspages.workjob.labour.LabourRate"/>',width:60,align:'center',
		styler: function(index,row){
			if (row.id != "footer" && row.labourrate==0){
				return 'background-color:#FFCCCC;';
			}
		},
		formatter:function(value,row,index){
		if(row.id == "footer"){
			return " ";
		}
		else{
			return "$" + value;
		}
		}},
	{field:'total',title:'<spring:message code="syspages.workjob.labour.LabourTotal"/>',width:100,align:'center',
		styler: function(index,row){
			if (row.id != "footer" && row.total==0){
				return 'background-color:#FFCCCC;';
			}
		},
		formatter:function(value,row,index){
			return "$" + value;
		}},
]] ,</span>

  • styler:对显示数据做样式更改;
<span style="font-size:18px;">styler: function(index,row){
	if (row.id != "footer" && row.total==0){
		return 'background-color:#FFCCCC;';
	}
}</span>
  • onLoadSuccess:function()对返回数据做统计。
<span style="font-size:18px;">onLoadSuccess:function(data){
	$('#easydiv'+num).attr("mainid",data.rows[0].jobcontentmainid);
	var data = $('#easydiv'+num).datagrid('getData');
	$('#divdiv'+num).css("height",35*(data.rows.length+5));
	$('#easydiv'+num).datagrid('resize');
	var rows = $('#easydiv'+num).datagrid('getFooterRows');
	rows[0]['productusage'] = '<strong> Workers </strong>';
	rows[0]['itemqty'] = '<strong> Weeks </strong>';
	rows[0]['buildlabourqty'] = '<strong> Days </strong>';
	rows[1]['productname'] = '<strong>Own labour Estimate </strong><input TYPE ="checkbox" id="estimate' + num +'" name ="estimate'+ num  +'" onClick="estimate(' + num +')"/>';
	rows[1]['productusage'] = '<INPUT TYPE="TEXT" value="0"  id="workers' + num +'" name="workers'+num +'" style="width: 100px" onBlur = "caculate(' + num +')" onkeyup="if(isNaN(value))execCommand(\'undo\')" />';
	rows[1]['itemqty'] = '<INPUT TYPE="TEXT"  value="0"  id="weeks' + num +'" name="weeks'+num +'" style="width: 60px" onBlur = "caculate(' + num +')" onkeyup="if(isNaN(value))execCommand(\'undo\')"/>';
	rows[1]['buildlabourqty'] = '<INPUT TYPE="TEXT"  value="0" s id="days' + num +'" name="days'+num +'" style="width: 60px" onBlur = "caculate(' + num +')" onkeyup="if(isNaN(value))execCommand(\'undo\')"/>';
	$('#easydiv'+num).datagrid('reloadFooter');
	if(data){
		$.each(data.rows, function(index, item){
			if(item.subcontractorlabour == 1){
				$('#easydiv'+num).datagrid('checkRow', index);
				var $tr = $('#easydiv'+num).prev().find("tr[datagrid-row-index=" + index + "]");
				$tr.css("background", "#ADD8E6");
			}
		});
	}
	var sizeOfShowtable = NumOfShowtable.length;
	NumOfShowtable[sizeOfShowtable] = num;
	$("[name = ck]:checkbox").bind("click",function () {
		var flag = $(this).prop("checked");
		var $tr = $(this).closest("tr");
		var rowindex = $tr.attr("datagrid-row-index");
		persubContractor(num,parseInt(rowindex),flag);
		if (flag) {
			$tr.css("background", "#ADD8E6");
		} else {
			$tr.css("background", "auto");
		}
	});
}</span>

创建方式:easyui官方文档):

从现有的表格元素创建DataGrid,在HTML中定义列、行和数据。

<span style="font-size:18px;"><table class="easyui-datagrid">
    <thead>
        <tr>
            <th data-options="field:'code'">编码</th>
            <th data-options="field:'name'">名称</th>
            <th data-options="field:'price'">价格</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>001</td><td>name1</td><td>2323</td>
        </tr>
        <tr>
            <td>002</td><td>name2</td><td>4612</td>
        </tr>
    </tbody>
</table>
</span>

通过<table>标签创建DataGrid控件。在表格内使用<th>标签定义列。

<span style="font-size:18px;"><table class="easyui-datagrid" style="width:400px;height:250px"
        data-options="url:'datagrid_data.json',fitColumns:true,singleSelect:true">
    <thead>
        <tr>
            <th data-options="field:'code',width:100">编码</th>
            <th data-options="field:'name',width:100">名称</th>
            <th data-options="field:'price',width:100,align:'right'">价格</th>
        </tr>
    </thead>
</table>
</span>

使用Javascript去创建DataGrid控件。(即:上面介绍的动态创建的方式)

html:

<span style="font-size:18px;"><table id="dg"></table></span>

js:

<span style="font-size:18px;">$('#dg').datagrid({
    url:'datagrid_data.json',
    columns:[[
        {field:'code',title:'Code',width:100},
        {field:'name',title:'Name',width:100},
        {field:'price',title:'Price',width:100,align:'right'}
    ]]
});
</span>

总结:

之前没怎么接触过js代码,所以每次做项目都会有一种恐惧感,每次都想提高,但是每次都会害怕,所以每次都绕道而行。实习总结了一句话:我们都愿意绕着问题跑,可若是绕开了,我们怎么提高啊……

时间: 2024-10-09 21:15:05

js动态创建DataGrid的相关文章

用JS动态创建登录表单,报了个小错误

后来发现原来是: dvObj.style.border='#Red 1px sold'; 其中的Red多谢了一个‘#’, 但是奇怪的是在chrome和firefox都备有报错,但是在ie中报错了. 各位仁兄美眉们一定要小心了额. 下面是这段js动态创建登录框的js代码: 1 onload = function () { 2 var dvObj = document.createElement('div'); 3 dvObj.style.border = 'Red 1px solid'; 4 dv

用JS动态创建SVG元素并绑定事件

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("width", "800"); svg.setAttribute("height", "500"); svg.addEventListener("load", function () {

js动态创建及移除div的方法

本文实例讲述了js动态创建及移除div的方法.分享给大家供大家参考.具体实现方法如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 //创建div function createDiv(){  if(document.getElementByIdx_x("newD")!=null)   document.body.removeChild(document.getElementByIdx_x(&q

js动态创建表格------Day59

刚刚不知道怎么回事,CSDN博客一直打不开,就在博客园完成了今天的记录,结果临关机,登录了下,发现又好了,就再多花个几分钟转下吧,也不管究竟在意的是什么了,权当强迫症了... 前几天记录了动态的添加一行一列:insertRow()和insertCell();动态的删除一行一列:deleteRow()和deleteCell():选中一行:this的参数传递,这些都是实现的关键,但是这一切都建立在一个基础上:那就是存在一个表格.今天就来记录下动态建立表格的方法: 事实上在刚开始的时候,我只想到了一个

给js动态创建的对象绑定事件

1.使用原生JS动态为动态创建的对象绑定事件 1-1.创建一个function,用来兼容IE8以下浏览器添加事件 function addEvent(el, type, fn) {  if(el.addEventListener){ el.addEventListener(type,fn,false) }else if(el.attachEvent()){ el.attachEvent('on' + type,fn,false) }else{ return false }} 1-2.使用JS创建

js 动态创建don对象学习

html部分 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <title></title> <!--<link href="css.css" type="text/css"

JS动态创建combobox

在平时的学习过程中没有怎么写过JS代码,因为不熟悉,所以多多少少对JS代码有一种恐惧.到了公司,铺天盖地的JS代码,简直让人哭笑不得.在这漫天都是JS代码的世界里,我也慢慢的见识了些许,以一个小功能先来热热身: 使用JS代码动态创建combobox,功能很简单就是使用ajax异步从后台获取数据,然后在前台显示就可是了,那么具体的JS代码如何写呢?后台的代码又如何写呢? Js: <span style="font-size:18px;">$dialog.find("

JS动态创建元素

动态创建元素的三种方法: 第一种document.write("") document.write("<input type=‘text’>  value='456'>"); 相当于创建了一个默认名是456的输入框 function f1(){        document.write("<input type='text' value='999999'>");    } 但是当document.write(&qu

JS动态创建元素的方式

动态创建元素的三种方式: 1.document.write(): a.写在函数里面的话,会冲刷掉之前的页面元素,所以一般不用或是少用: b.会打开document.open()或关闭document.close()文档流: c.文档流: 默认的浏览器的加载顺序是从上往下依次加载的,把当前页面加载完毕之后,就相当于关闭了文档流. 例: <input type="text" value="123"/><input type="button&q