用JavaScript動態實現單元格合併
阿新 • • 發佈:2018-12-15
不太想描述,大家自行理解吧,這樣可能記憶會深一點兒~
<script type="text/javascript"> function mergeCells(){ var count = 0; var oldText = ''; var oldTd; var count2 = 0; var oldText2 = ''; var oldTd2; var isDelete = false; var trs = document.getElementsByTagName("tr"); for ( var i = 0; i < trs.length; i++) {var tds = trs[i].getElementsByTagName("td"); if(count == 0){ oldText = tds[0].innerHTML; oldTd = tds[0]; count = 1; }else if(oldText != tds[0].innerHTML){ oldTd.rowSpan = count; oldText = tds[0].innerHTML; oldTd = tds[0]; count= 1; }else{ count = count + 1; tds[0].parentNode.removeChild(tds[0]); isDelete = true; } if(i == trs.length - 1){ oldTd.rowSpan = count; } /*添加了一個isDelete變數,用於判斷是否刪除元素*/ if(count2 == 0){ oldText2= tds[1].innerHTML; oldTd2 = tds[1]; count2 = 1; }else if(isDelete){ if(oldText2 != tds[0].innerHTML){ oldTd2.rowSpan = count2; oldText2 = tds[0].innerHTML; oldTd2 = tds[0]; count2 = 1; }else{ count2 = count2 + 1; tds[1].parentNode.removeChild(tds[0]); } isDelete = false; }else{ if(oldText2 != tds[1].innerHTML){ oldTd2.rowSpan = count2; oldText2 = tds[1].innerHTML; oldTd2 = tds[1]; count2 = 1; }else{ count2 = count2 + 1; tds[1].parentNode.removeChild(tds[1]); } } if(i == trs.length - 1){ oldTd2.rowSpan = count2; } } } mergeCells(); </script>