标签:rowspan his 分享图片 The def [1] isp utf-8 ack
方法一:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 9 <table id="table1"> 10 <tr> 11 <td>111</td> 12 <td>222</td> 13 <td>333</td> 14 </tr> 15 <tr> 16 <td>111</td> 17 <td>555</td> 18 <td>333</td> 19 </tr> 20 <tr> 21 <td>111</td> 22 <td>888</td> 23 <td>333</td> 24 </tr> 25 <tr> 26 <td>aaa</td> 27 <td>bbb</td> 28 <td>333</td> 29 </tr> 30 </table> 31 32 <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> 33 <script> 34 35 jQuery.fn.rowspan = function(colIdx) { //封装的一个JQuery小插件 36 return this.each(function(){ 37 var that; 38 $(‘tr‘, this).each(function(row) { 39 $(‘td:eq(‘+colIdx+‘)‘, this).filter(‘:visible‘).each(function(col) { 40 if (that!=null && $(this).html() == $(that).html()) { 41 rowspan = $(that).attr("rowSpan"); 42 if (rowspan == undefined) { 43 $(that).attr("rowSpan",1); 44 rowspan = $(that).attr("rowSpan"); } 45 rowspan = Number(rowspan)+1; 46 $(that).attr("rowSpan",rowspan); 47 $(this).hide(); 48 } else { 49 that = this; 50 } 51 }); 52 }); 53 }); 54 } 55 $(function() { 56 $("#table1").rowspan(0);//传入的参数是对应的列数从0开始 第一列合并相同 57 // $("#table1").rowspan(1);//传入的参数是对应的列数从0开始 第二列合并相同 58 }); 59 </script> 60 61 </script> 62 </html>
合并前:
合并后:(根据实际项目需求,只合并第一列)
方法二:
1 function hb() { 2 var tab = document.getElementById("subtable"); 3 var maxCol = 3, val, count, start; 4 var ys = ""; 5 for (var col = maxCol - 1; col >= 0 ; col--) { 6 count = 1; 7 val = ""; 8 for (var i = 0; i < tab.rows.length; i++) { 9 if (val == tab.rows[i].cells[col].innerHTML) { 10 count++; 11 } else { 12 if (count > 1) { 13 //合并 14 start = i - count; 15 if (ys == "#00FFFF") { 16 ys = "#EEEE00"; 17 } else { 18 ys = "#00FFFF"; 19 } 20 tab.rows[start].cells[col].rowSpan = count; 21 tab.rows[start].cells[1].style.backgroundColor = ys;//改变颜色 22 // ys="#EEEE00"; 23 // tab.rows[i].cells[1].style.backgroundColor="#00FFFF";//改变颜色绿色 24 for (var j = start + 1; j < i; j++) { // 25 tab.rows[j].cells[col].style.display = "none"; 26 tab.rows[j].removeChild(tab.rows[j].cells[col]); 27 } 28 count = 1; 29 } 30 val = tab.rows[i].cells[col].innerHTML; 31 } 32 } 33 34 if (count > 1) { //合并,最后几行相同的情况下 35 start = i - count; 36 tab.rows[start].cells[col].rowSpan = count; 37 for (var j = start + 1; j < i; j++) { 38 tab.rows[j].removeChild(tab.rows[j].cells[col]); 39 } 40 } 41 } 42 }
第一种方法,仅用20行代码就可实现该功能,而且封装在jq库里面,其他页面可以直接调用。
第二种方法比较复杂,而且会把tabel里面所有相同列都合并,不实用。但是思路可以学习一下。
标签:rowspan his 分享图片 The def [1] isp utf-8 ack
原文地址:https://www.cnblogs.com/LiuLiangXuan/p/9300411.html