jQuery EasyUI 应用 - 创建 CRUD 数据网格(DataGrid)


jQuery EasyUI 应用 - 创建 CRUD 数据网格(DataGrid)

简介

jQuery EasyUI 是一组功能丰富、高效而易于学习的 jQuery 扩展集合,其中的 DataGrid 控件提供了创建 CRUD(增、删、改、查)数据网格的方法,十分实用。

本文将介绍如何使用 jQuery EasyUI 中的 DataGrid 控件,创建一个 CRUD 数据网格。

步骤

步骤 1:引入 jQuery EasyUI 库文件

首先,在 HTML 页面的 head 标签中引入 jQuery、EasyUI 和相关样式文件:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-easyui/1.9.14/themes/default/easyui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-easyui/1.9.14/themes/icon.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easyui/1.9.14/jquery.easyui.min.js"></script>

步骤 2:创建 HTML 页面布局

在 HTML 页面中创建一个容器 div,并设置其 id 为 dg:

<div id="dg"></div>

步骤 3:定义 DataGrid 控件

在 JavaScript 中创建 DataGrid 控件,并传入相应的参数,例如:

$('#dg').datagrid({
    url: 'data.php',
    title: 'Student List',
    width: '100%',
    height: 400,
    fitColumns: true,
    columns: [[
        { field: 'id', title: 'ID', width: 50 },
        { field: 'name', title: 'Name', width: 100, editor: 'text' },
        { field: 'age', title: 'Age', width: 50, editor: { type: 'numberbox', options: { precision: 0 } } },
        { field: 'gender', title: 'Gender', width: 50, editor: { type: 'combobox', options: { data: [{ value: 'Male', text: 'Male' }, { value: 'Female', text: 'Female' }] } } }
    ]],
    toolbar: [{
        text: 'Add',
        iconCls: 'icon-add',
        handler: function() {
            // todo: add record
        }
    }, '-', {
        text: 'Edit',
        iconCls: 'icon-edit',
        handler: function() {
            // todo: edit record
        }
    }, '-', {
        text: 'Delete',
        iconCls: 'icon-remove',
        handler: function() {
            // todo: delete record
        }
    }]
});

其中,“url” 参数指定获取数据的 URL 地址;“title” 参数定义数据网格的标题;“width” 和 “height” 参数分别定义数据网格的宽度和高度。

“columns” 参数定义数据网格展示的列信息,包含列的名称、宽度、编辑类型等。“editor” 属性可以为相应的列指定编辑器类型,例如上面通过 “combobox” 定义了一个下拉框。

“toolbar” 参数定义数据网格的工具栏,包含添加、编辑和删除等功能按钮,点击对应按钮触发相应的事件,对数据进行增、删、改的操作。

步骤 4:实现 CRUD 操作

在 DataGrid 控件的工具栏按钮中设置对应的事件,例如:

handler: function() {
    // 添加记录
    $('#dg').datagrid('appendRow',{});
    // 编辑记录
    $('#dg').datagrid('beginEdit', rowIndex);
    // 删除记录
    $('#dg').datagrid('deleteRow', rowIndex);
}

其中,“rowIndex” 是选中行的索引,可以使用以下方法获取用户选中行的索引:

var rows = $('#dg').datagrid('getSelections');
var rowIndex = $('#dg').datagrid('getRowIndex', rows[0]);

步骤 5:运行程序

将 HTML 页面保存,通过浏览器打开该页面即可看到创建的 CRUD 数据网格。可以查看、添加、编辑和删除相应的记录,实现对数据的增、删、改、查的操作。

总结

本文介绍了使用 jQuery EasyUI 中的 DataGrid 控件创建 CRUD 数据网格的方法,通过设置相应的参数和工具栏按钮事件能够实现对数据的增、删、改、查等操作,增加了 Web 应用的交互性和灵活性。