最近筆者在做一個後臺管理系統,頁面採用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日國慶節,在此,祝福我們偉大的祖國繁榮富強、國泰民安,同時也是筆者結婚二週年紀念日,小小博客一篇,獻給我們偉大的祖國,以及由我賢惠老婆和可愛兒子組成的小家。