jQuery EasyUI 数据网格 - 添加复选框


jQuery EasyUI 数据网格 - 添加复选框

概述

在数据展示时,很多场景下需要选择多个数据进行操作。为此,我们可以自定义数据网格的列,添加复选框。jQuery EasyUI 提供了简单易用的方式来实现这一需求。

实现

  1. 在数据网格中增加 column;

  2. 使用 formatter 将列的数据项渲染为复选框。

下面是一份添加复选框的示例代码:

<table id="dataGrid"></table>
$("#dataGrid").datagrid({
    url: "data.json",
    method: "get",
    columns: [[
        {field: "id", title: "ID", width: 50},
        {field: "name", title: "Name", width: 100},
        {field: "age", title: "Age", width: 50},
        {field: "gender", title: "Gender", width: 50},
        {field: "email", title: "Email", width: 100},
        {
            field: "check", title: "Check",
            width: 50,
            formatter: function (value, rowData, rowIndex) {
                return '<input type="checkbox" name="ckbox" value="' + rowData.id + '">';
            }
        }
    ]],
    pagination: true,
    rownumbers: true
});

在上述代码中,我们添加了一个名为 check 的列,并使用 formatter 函数将列的数据项渲染为复选框。其代码为:

formatter: function (value, rowData, rowIndex) {
                return '<input type="checkbox" name="ckbox" value="' + rowData.id + '">';
            }

checkbox 自身并不能获取到选中状态。因此,我们可以在选中行事件中,将选中的行对应的复选框选中。

$("#dataGrid").datagrid("getPanel").on("click", "input[name='ckbox']", function() {
    if ($(this).attr("checked")) {
        $(this).attr("checked", false);
    } else {
        $(this).attr("checked", true);
    }
});

至此,我们的数据网格就添加了复选框。

总结

使用 jQuery EasyUI 数据网格添加复选框十分简单。只需添加 column 和使用 formatter 渲染相关的列即可。

同时,考虑到复选框的选中状态,我们可以在选中行事件中绑定处理函数,实现选中行对应的复选框选中。