首先说明下需求,不同的需求可能实现不一样。我的需求是同学问我如何通过后台动态的配置,然后动态的生成前台的html table。因为他们的前台页面是写死的,表格的每一行每一列,除了数据。我们先来看看数据情况。他希望一级二级指标和三级指标内容发生变化时,也就是动态的添加一级,二级,三级指标时,如何实现一级二级的合并效果。这个问题一开始我上网搜索excel模板转换...
首先说明下需求,不同的需求可能实现不一样。
我的需求是同学问我如何通过后台动态的配置,然后动态的生成前台的html table。
因为他们的前台页面是写死的,表格的每一行每一列,除了数据。
我们先来看看数据情况。
他希望一级二级指标和三级指标内容发生变化时,也就是动态的添加一级,二级,三级指标时,如何实现一级二级的合并效果。
这个问题一开始我上网搜索excel模板转换html。。但是转换都是固定的内容,也就是模板固定了。动态填充数据是不可能的。
要填充也是单元格填充,不能内容完全动态。
基于这个需求,我自己写了一个html的例子。也不是完全的动态,手动的指定 了第一列和第二列为标题列。
原理是:将每一列及其对应的合并行数读出来,然后,判断第一列和第二列的名称,如果第一次处理,就添加td 且rowspan。
否则,就只添加第三列的td。
废话不多说,,上代码。。(模拟数据见代码)
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <style> *{ padding:0px; margin:0px; } table{ width:100%; height:100%; } table td{ text-align:center; border:solid 1px; } </style> </head> <body> <table> <thead> <tr><td>列1</td><td>列2</td><td>列3</td></tr> </thead> <tbody id="tb"> </tbody> </table> <script> var json=[ {"t1":{"t":"a1","rows":5},"t2":{"t":"b1","rows":3},"t3":{"t":"c1","rows":1}}, {"t1":{"t":"a1","rows":5},"t2":{"t":"b1","rows":3},"t3":{"t":"c2","rows":1}}, {"t1":{"t":"a1","rows":5},"t2":{"t":"b1","rows":3},"t3":{"t":"c3","rows":1}}, {"t1":{"t":"a1","rows":5},"t2":{"t":"b2","rows":2},"t3":{"t":"c4","rows":1}}, {"t1":{"t":"a1","rows":5},"t2":{"t":"b2","rows":2},"t3":{"t":"c5","rows":1}} ]; //json = JSON.parse(json); draw(json); function draw(json){ var t1='',t2=''; $.each(json,function(i,item){ var html = '<tr>'; if(t1=='' || t1!=item.t1.t){ html += '<td rowspan="'+item.t1.rows+'">'+item.t1.t+'</td>'; t1 = item.t1.t; } if(t2=='' || t2!=item.t2.t){ html += '<td rowspan="'+item.t2.rows+'">'+item.t2.t+'</td>'; t2 = item.t2.t; } html += '<td>'+item.t3.t+'</td>'; html +='</tr>'; $('#tb').append(html); }); } </script> </body> </html>
阅读全文