原生JS 实现表格的合并单元格

  /*
            参数:table或tbody的id,开始行号,结束行号,合并哪一列
   mc('field_selection', 0, 4, 0);
            */
            //--------合并单元格

            function mc(table1, startRow, endRow, col) {
                var tb = document.getElementById(table1);
                let tableCellLength = tb.rows[0].cells.length;
                for (let i = startRow; i < endRow; i++) {
                    if (tb.rows[startRow].cells[col].innerHTML == tb.rows[i + 1].cells[col].innerHTML) {
                        //合并最后一列相同的行
                        tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[tableCellLength-1]);
                        tb.rows[startRow].cells[tableCellLength-1].rowSpan = (tb.rows[startRow].cells[tableCellLength-1].rowSpan | 0) + 1;
                        //合并第col列相同的行    
                        tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[col]);
                        tb.rows[startRow].cells[col].rowSpan = (tb.rows[startRow].cells[col].rowSpan | 0) + 1;
                    }else{
                        mc(table1, i + 1, endRow, col)
                    }
                }
            }//mc(table1, startRow, endRow, col)

你可能感兴趣的:(javascript)