日期:2014-05-16  浏览次数:20472 次

js 实现根据数组分组动态生成table(合并相同项)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script>
  //xxbh:学校编号,bjbh:班级编号,xx:姓名
	var arrJson=[
		{'xxbh':'1001','bjbh':'0801','xx':'李四'},{'xxbh':'1001','bjbh':'0802','xx':'张三'},
		{'xxbh':'1003','bjbh':'0803','xx':'王五'},{'xxbh':'1003','bjbh':'0804','xx':'晶晶'},
		{'xxbh':'1005','bjbh':'0701','xx':'亮亮'},{'xxbh':'1002','bjbh':'0701','xx':'明敏'},
		{'xxbh':'1005','bjbh':'0701','xx':'张灿'},{'xxbh':'1002','bjbh':'0801','xx':'小白'},
		{'xxbh':'1005','bjbh':'0802','xx':'小胖'},{'xxbh':'1002','bjbh':'0901','xx':'小丽'},
		{'xxbh':'1003','bjbh':'0901','xx':'阿宝'},{'xxbh':'1004','bjbh':'0901','xx':'王泰'},
		{'xxbh':'1001','bjbh':'0901','xx':'阿毛'},{'xxbh':'1006','bjbh':'0901','xx':'李铭'},
		{'xxbh':'1005','bjbh':'0901','xx':'阿城'},{'xxbh':'1004','bjbh':'0901','xx':'张晓'},
		{'xxbh':'1006','bjbh':'0901','xx':'小小'},{'xxbh':'1004','bjbh':'0901','xx':'白昼'},
		{'xxbh':'1002','bjbh':'0901','xx':'乐乐'},{'xxbh':'1001','bjbh':'0901','xx':'黎明'}
	];
	function creatMapByXxbh(arrJson){
		var xxbhMap={};
		var len = arrJson.length;
		for(var i=0;i<len;i++){
		
			if(xxbhMap[arrJson[i].xxbh] == undefined){
				var list = [];
				list.push(arrJson[i]);
				xxbhMap[arrJson[i].xxbh] = list;
			}else{
				xxbhMap[arrJson[i].xxbh].push(arrJson[i]);
			}
			
		}
		var str="<table border='1'><tr><td width='200'>学校编号</td><td width='200'>班级</td><td width='200'>姓名</td></tr>";
		for(var xxbh in xxbhMap){
			var stu = xxbhMap[xxbh];
			alert(stu.length);
			str+="<tr><td rowspan='"+stu.length+"'>"+xxbh+"</td>";
			for(var i = 0;i < stu.length;i++){
				//document.write(xxbh + " "+stu[i].bjbh+" "+stu[i].xx +"<br />")
				//document.write("<table><tr><td>学校编号</td><td>班级</td><td>姓名</td></tr></table> ")
				if(i==0){
					str+="<td>"+stu[i].bjbh+"</td><td>"+stu[i].xx+"</td></tr>";
				}else{
					str+="<tr><td>"+stu[i].bjbh+"</td><td>"+stu[i].xx+"</td></tr>";
				}	
			}
			str+="<tr ><td colspan='3'>"+xxbh+"共有"+stu.length+"个班级</td></tr>"
		}
		str+="</table> ";
		document.write(str)
	}
  </script>
 </head >

 <body>
  <button onclick='creatMapByXxbh(arrJson)'>测试</button> 
 </body>
</html>
?


?
?