【JQuery】实现table中内容相同的行列自动合并

JQuery实现table中内容相同的行列自动合并

源数据表格效果

【JQuery】实现table中内容相同的行列自动合并

<script>
/* 合并指定列中相同的内容 */
$.fn.rowspan = function (colIdx) {
        return this.each(function () {
            var that;
            $('tr', this).each(function (row) {
                $('td:eq(' + colIdx + ')', this).filter(':visible').each(function (col) {
                    if (that != null && $(this).html() == $(that).html()) {
                        rowspan = $(that).attr("rowSpan");
                        if (rowspan == undefined) {
                            $(that).attr("rowSpan", 1);
                            rowspan = $(that).attr("rowSpan");
                        }
                        rowspan = Number(rowspan) + 1;
                        $(that).attr("rowSpan", rowspan);
                        $(this).hide();
                    } else {
                        that = this;
                    }
                });
            });
        });
    }

/* 合并指定列范围内的行 */
$.fn.colspan = function (s, e) {
        return this.each(function () {
            var that;
            $('tr', this).each(function (row) {
                $('td:gt(' + s + '):lt(' + e + ')', this).filter(':visible').each(function (col) {
                    if (that != null && $(this).html() == $(that).html()) {
                        colspan = $(that).attr("colSpan");
                        if (colspan == undefined) {
                            $(that).attr("colSpan", 1);
                            colspan = $(that).attr("colSpan");
                        }
                        colspan = Number(colspan) + 1;
                        $(that).attr("colSpan", colspan);
                        $(this).hide();
                    } else {
                        that = this;
                    }
                });
            });
        });
    }
</script>
/* 当表格加载完成后 执行以下代码调用合并 */

/* 前9列	合并相同内容的列 */
	i = 8;
	while (i >= 0) { $("#table1").rowspan(i--); }
	
	/* 8 9 10 三列	合并相同内容的行 */
	$("#table1").colspan(6, 3);
合并后数据表格效果

【JQuery】实现table中内容相同的行列自动合并