在 jQuery EasyUI 中,你可以通过修改 DataGrid 的列定义来动态改变列。以下是一个简单的例子,演示了如何通过 JavaScript 动态改变 EasyUI DataGrid 的列:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery EasyUI 动态改变列示例</title>
    <!-- 引入 jQuery 库 -->
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- 引入 EasyUI 样式和脚本文件 -->
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>

    <!-- 创建 EasyUI Datagrid -->
    <table id="datagrid" class="easyui-datagrid" style="width:100%;height:300px"
           url="your_data_url"
           pagination="true"
           rownumbers="true"
           fitColumns="true"
           singleSelect="true">
        <thead>
            <tr>
                <!-- 初始列定义 -->
                <th field="column1" width="100">列1</th>
                <th field="column2" width="100">列2</th>
                <th field="column3" width="100">列3</th>
                <!-- 添加更多列... -->
            </tr>
        </thead>
    </table>

    <!-- 按钮触发动态改变列 -->
    <button onclick="changeColumns()">改变列</button>

    <!-- JavaScript 部分 -->
    <script type="text/javascript">
        // JavaScript 代码

        // 示例:动态改变列
        function changeColumns() {
            // 获取 Datagrid 对象
            var datagrid = $('#datagrid');

            // 定义新的列定义
            var newColumns = [
                {field:'column1',title:'新列1',width:120},
                {field:'column3',title:'新列3',width:120},
                {field:'column4',title:'新列4',width:120},
                // 添加更多新列...
            ];

            // 更新列定义
            datagrid.datagrid('reload').datagrid('loadData', { total: 0, rows: [] });
            datagrid.datagrid({
                columns: [newColumns]
            });
        }
    </script>

</body>
</html>

在上述代码中,我添加了一个按钮,当按钮被点击时,调用 changeColumns 函数。该函数首先获取到 DataGrid 对象,然后定义了新的列定义 newColumns。最后,通过调用 datagrid.datagrid('reload').datagrid('loadData', { total: 0, rows: [] }); 来清空 DataGrid 的数据,然后使用 datagrid.datagrid({columns: [newColumns]}); 来更新列定义。

请注意,这种方式可能会导致数据重新加载,因此在实际应用中,你可能需要保存和恢复用户的一些操作状态。确保替换 "your_data_url" 为实际数据源的 URL,并根据你的需求修改列的名称和数量。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13109/jQuery EasyUI