JS table内容转成二维数组,支持colspan和rowspan
思路:
1.先初始化colspan的数据到数组
2.根据rowspan和colspan计算th和td的矩阵二次填充数组
说明:
需要引用到第三方库jQuery,table中的th和td行和列跨度必须正确
1 <!-- 演示数据部分 --> 2 <table id="expTable" class="table table_hover table_border table_center"> 3 <tbody> 4 <tr class="head"> 5 <th>客户</th> 6 <th class="bb_header">期初余额</th> 7 <th colspan="2">订单金额</th> 8 <th>收款金额</th> 9 <th>收款账户</th> 10 <th>客户余额</th> 11 <th>备注</th> 12 </tr> 13 <tr> 14 <td rowspan="2">新月</td> 15 <td>21</td> 16 <td rowspan="3">22</td> 17 <td>23</td> 18 <td>24</td> 19 <td>25</td> 20 <td>26</td> 21 <td></td> 22 </tr> 23 <tr> 24 <td>31</td> 25 <td>32</td> 26 <td>33</td> 27 <td>34</td> 28 <td>35</td> 29 <td></td> 30 </tr> 31 <tr> 32 <td>合计</td> 33 <td>41</td> 34 <td>42</td> 35 <td>43</td> 36 <td>-</td> 37 <td>45</td> 38 <td></td> 39 </tr> 40 41 </tbody> 42 </table>
1 //获取table内容并转成二维数组(支持colspan和rowspan) 2 function getTabArray(tabId) { 3 var data = []; 4 if ($(tabId + ' tr').length == 0) { 5 return data; 6 } 7 //填充数组 8 $(tabId + ' tr').each(function () { 9 var arr = []; 10 $(this).children('th,td').each(function () { 11 arr.push($(this).text().trim()); 12 if ($(this).attr('colspan')) { 13 for (var i = 0, len = parseInt($(this).attr('colspan')) - 1; i < len; i++) { 14 arr.push(''); 15 } 16 } 17 }); 18 data.push(arr); 19 }); 20 //二次填充 21 var yIndex = 0; 22 $(tabId + ' tr').each(function () { 23 var xIndex = 0; 24 $(this).children('th,td').each(function () { 25 var t_yIndex = 0; 26 if ($(this).attr('rowspan')) { 27 t_yIndex = parseInt($(this).attr('rowspan')); 28 } 29 30 for (var i = 1, len = t_yIndex; i < len; i++) { 31 var arr = data[yIndex + i]; 32 arr.splice(xIndex, 0, ''); 33 } 34 35 if ($(this).attr('colspan')) { 36 xIndex += parseInt($(this).attr('colspan')); 37 } else { 38 xIndex++; 39 } 40 }); 41 yIndex++; 42 }); 43 return data; 44 }
1 //测试调用显示到console 2 getCvsData() 3 function getCvsData() { 4 var data = getTabArray('#expTable'); 5 var cvsLines = ''; 6 for (var i = 0, len = data.length; i < len; i++) { 7 cvsLines += data[i].join(',') + '\n'; 8 } 9 10 //debug 11 for (var i = 0, len = data.length; i < len; i++) { 12 console.info(data[i].join(',')); 13 } 14 return cvsLines; 15 }
声明:本文为原创文章,如需转载,请注明来源并保留原文链接