最近笔者在做一个后台管理系统,页面采用JSP+jQuery+JSTL来渲染,其中遇到一个需求点,即表格动态合并,即把表格中相同的多个列合并成一个列,目的是让表格更清晰,实现过程不易,主要是技术点有点分散,查资料比较麻烦,故此笔者下面做个简述,供其他小伙伴参考,节约时间。
一,首先完成基本表格,即原始的表格,笔者使用Boostrap实现,如下:
二,针对已完成的表格做合并处理,如上图,即将 主题代号和主题内容 部分做合并,具体查询资料过程就不说了,核心点就是通过jQuery不断的做循环判断来实现,实现代码如下:
//需要合并的表格
<td class="hebing">${themeAttribute.theme.code}</td>
//这里采用jQuery方式实现:
<script type="text/javascript">
$(function () {
$('.hebing').each(function (index, element) {
if (!$(this).hasClass('hide')) {
var next = $(this).parent('tr').next('tr').children('.hebing');//下一个合并的对象
$(this).attr('rowspan', 1);
while ($(this).text() == next.text()) {
$(this).attr('rowspan', parseInt($(this).attr('rowspan')) + 1);
next.hide();
next.addClass('hide');
next = next.parent('tr').next('tr').children('.hebing');//下一个合并的对象
}
}
});
</script>
具体效果如下:
这里参考资料来源这里,大家可以去看看:https://bbs.csdn.net/topics/391853115 ,很感谢作者的分享精神,但是很明显,这里没有让合并后的表格垂直居中,就不太好了,下一步我们来实现。
三、jQuery实现合并后,基本已经满足了笔者需求,但是为了更加美观,就需要把合并后的列做合并处理,具体实现笔者这里总结了三种方式:
第一种:传统CSS样式表;
<head>
<style type="text/css">
.table th,
.table td {
text-align: center;
vertical-align: middle !important;
}
</style>
</head>
第二种:最简单直接的方式:
<td class="hebing" style="vertical-align: middle !important;text-align: center;">${themeAttribute.theme.code}</td>
第三种:jQuery属性赋值方式:
$(this).attr('style', "vertical-align: middle !important;text-align: center;");
综上笔者认为第三种方式最优雅,那么最终实现效果代码如下:
<script type="text/javascript">
$(function () {
$('.hebing').each(function (index, element) {
if (!$(this).hasClass('hide')) {
var next = $(this).parent('tr').next('tr').children('.hebing');//下一个合并的对象
$(this).attr('rowspan', 1);
$(this).attr('style', "vertical-align: middle !important;text-align: center;");
while ($(this).text() == next.text()) {
$(this).attr('rowspan', parseInt($(this).attr('rowspan')) + 1);
next.hide();
next.addClass('hide');
next = next.parent('tr').next('tr').children('.hebing');//下一个合并的对象
}
}
});
});
</script>
至此,笔者所要的需求完美实现,最终页面效果如下:
另附:今天是2019年10月01日国庆节,在此,祝福我们伟大的祖国繁荣富强、国泰民安,同时也是笔者结婚二周年纪念日,小小博客一篇,献给我们伟大的祖国,以及由我贤惠老婆和可爱儿子组成的小家。