Jquery.dataTables数据表格设置复合表头

如题在使用Jquery.dataTables数据表格时,由于数据列比较多需要使用复合表头来区分,直接使用colspanrowspan发现数据表格没有正常渲染,且浏览器控制台出现报错:
Uncaught TypeError: Carnot read properties of undefined (reading style )

下面展示html和渲染数据表格的js代码:

错误代码:

<table id="dataTableList" class="table table-bordered table-hover dataTable">
    <thead>
    <tr>
        <th rowspan="3" class="text-center">所在区域</th>
        <th rowspan="3" class="text-center">所属公司</th>
        <th rowspan="3" colspan="2" class="text-center">所属项目</th>
        <th colspan="4" class="text-center">项目人员</th>
        <th rowspan="3" class="text-center">项目总人数</th>
    </tr>
    <tr>
        <th colspan="2" class="text-center">开发部</th>
        <th colspan="2" class="text-center">测试部</th>
    </tr>
    <tr>
        <th  class="text-center">普通人员</th>
        <th  class="text-center">管理人员</th>
        <th  class="text-center">普通人员</th>
        <th  class="text-center">管理人员</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>
<script>
$('#dataTableList').DataTable({
    ajax: {
        url: 'localhost:8080/getList'
    },
    columns: [
        {data: "area"},
        // 省略
    ],
    paging: false,
    ordering: false,
    info: false,
    searching: false,
    scrollX: true,
    scrollY: "400px",
    scrollCollapse: true,
    fixedHeader: true, // 固定首行
});
</script>

页面效果图:
在这里插入图片描述
报错信息:
在这里插入图片描述


    从控制台给出的报错信息,可以知道错误是指向了jguery. dataTables.is:5292:7处,经过分析源码发现是dataTables在循环处理<th>表头时出错,元素为空。

    最后又排查了一遍代码发现,dataTables数据表格的表头渲染是根据<thead>中的第一行<tr>来进行渲染的,但是在第一行<tr>中我们设置了colspanrowspan属性会导致实际上<th>的数量与数据列的数量不一致
    此时只需增加一个<tr>元素,设置正确的<th>数量,同时进行隐藏不影响页面展示即可。
纠正后的代码如下:


正确代码如下:

<table id="dataTableList" class="table table-bordered table-hover dataTable">
    <thead>
    <tr style="display: none">
		<th></th>
		<th></th>
		<th></th>
		<th></th>
		<th></th>
		<th></th>
		<th></th>
		<th></th>
	</tr>
    <tr>
        <th rowspan="3" class="text-center">所在区域</th>
        <th rowspan="3" class="text-center">所属公司</th>
        <th rowspan="3" colspan="2" class="text-center">所属项目</th>
        <th colspan="4" class="text-center">项目人员</th>
        <th rowspan="3" class="text-center">项目总人数</th>
    </tr>
    <tr>
        <th colspan="2" class="text-center">开发部</th>
        <th colspan="2" class="text-center">测试部</th>
    </tr>
    <tr>
        <th  class="text-center">普通人员</th>
        <th  class="text-center">管理人员</th>
        <th  class="text-center">普通人员</th>
        <th  class="text-center">管理人员</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

修改代码后重新编译刷新页面,发现浏览器控制台已经没有报错,数据表格的复合表头也可以正常渲染出现。

完结~撒花✿✿✿

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值