JQuery Table 合并单元格-解决Bug版本
网络中提供的方法是:
<script type="text/javascript"> function _w_table_rowspan(_w_table_id, _w_table_colnum) { _w_table_firsttd = ""; _w_table_currenttd = ""; _w_table_SpanNum = 0; _w_table_Obj = $(_w_table_id + " tr td:nth-child(" + _w_table_colnum + ")"); _w_table_Obj.each(function (i) { if (i == 0) { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } else { _w_table_currenttd = $(this); if (_w_table_firsttd.text() == _w_table_currenttd.text()) { _w_table_SpanNum++; _w_table_currenttd.hide(); //remove(); _w_table_firsttd.attr("rowSpan", _w_table_SpanNum); } else { _w_table_firsttd = $(this); _w_table_SpanNum = 1; } } }); } $(document).ready(function () { _w_table_rowspan("#HZ", 1); _w_table_rowspan("#HZ", 2); _w_table_rowspan("#HZ", 3); }); </script>
但这个方式存在一个bug,纯单元格的合并,不管是不是一组的,例如下面的表格,合并出来就有问题:
1 | A | E | ||
1 | A | E | ||
1 | A | E | ||
2 | B | E | ||
2 | B | E | ||
2 | B | E | ||
3 | B | E | ||
3 | C | E |
如果用上面的代码合并就变成这个样子了:
1 | A | E | ||
2 | B | |||
3 | ||||
C |
我们希望是:
1 | A | E | ||
B | ||||
2 | B | E | ||
3 | B | E | ||
C |
所以只需要做少许变更便可达到目的,在合并的时候判断上下单元格值得时候携带左边的单元格一起判断:
修改后的代码如下:
function _w_table_rowspan(_w_table_id, _w_table_colnum) { _w_table_firsttd = ""; _w_table_currenttd = ""; _w_table_SpanNum = 0; _w_table_Obj = $(_w_table_id + " tr td:nth-child(" + _w_table_colnum + ")"); _w_table_PreObj = $(_w_table_id + " tr td:nth-child(" + (_w_table_colnum == 1 ? 1 : _w_table_colnum - 1) + ")"); _w_table_Prefirsttd = ""; _w_table_Obj.each(function (i) { if (i == 0) { _w_table_firsttd = $(this); _w_table_Prefirsttd = $(_w_table_PreObj[0]); _w_table_SpanNum = 1; } else { _w_table_currenttd = $(this); if (_w_table_Prefirsttd.text() + "-" + _w_table_firsttd.text() == $(_w_table_PreObj[i]).text() + "-" + _w_table_currenttd.text()) { if ($(_w_table_PreObj[i]).text() + "-" + _w_table_currenttd.text() != "-") { _w_table_SpanNum++; _w_table_currenttd.hide(); //remove(); _w_table_firsttd.attr("rowSpan", _w_table_SpanNum); } } else { _w_table_firsttd = $(this); _w_table_Prefirsttd = $(_w_table_PreObj[i]); _w_table_SpanNum = 1; } } }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架