You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让DataTable响应式表格除最后一列外点击均可切换折叠

解决DataTables响应式表格多列触发折叠/展开的问题

要实现除最后一列(Action列)外,其余列点击均可切换折叠/展开状态,同时保留最后一列的操作功能,只需修改DataTables的初始化配置,指定触发详情的单元格选择器即可:

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.7/css/jquery.dataTables.min.css">
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.7/js/jquery.dataTables.min.js"></script>
</head>
<body>
    <table id="example" class="display responsive nowrap" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>John Doe</td>
                <td>30</td>
                <td><button onclick="performAction()">Do Action</button></td>
            </tr>
            <tr>
                <td>Jane Smith</td>
                <td>25</td>
                <td><button onclick="performAction()">Do Action</button></td>
            </tr>
        </tbody>
    </table>
    <script>
        $(document).ready( function () {
            var table = $('#example').DataTable({
                // 配置响应式详情的触发选择器:排除最后一列的所有单元格
                responsive: {
                    details: {
                        selector: 'td:not(:last-child)'
                    }
                }
            });
        });

        function performAction() {
            // 执行自定义操作
            alert("Action performed!");
        }
    </script>
</body>
</html>

关键说明

  • 通过responsive.details.selector配置项,指定td:not(:last-child)作为触发折叠/展开的元素,即除最后一列外的所有单元格点击都能切换子行状态
  • 最后一列的按钮点击事件不受影响,因为该列不在触发选择器范围内,点击按钮会正常执行performAction()函数

如果需要更精准的列控制(比如仅允许某几列触发),可以将选择器改为具体列索引,例如td:nth-child(1), td:nth-child(2),但当前需求用td:not(:last-child)最简洁。

内容的提问来源于stack exchange,提问作者always-a-learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:13:14