jQuery EasyUI 数据网格列运算实现教程

iPython
iPython
发布时间:2026-10-15| 4人浏览过
原创

在数据表格中,经常需要根据用户输入自动计算并显示衍生列的值。本文通过 jQuery EasyUI 的 datagrid 组件,演示如何在可编辑行中实现列间自动运算,帮助开发者快速构建动态数据表格。

创建可编辑数据网格

首先,使用 HTML 表格结构初始化一个可编辑的 datagrid。其中,listprice(单价)、amount(数量)和 unitcost(总价)列均配置为 numberbox 编辑器,支持数值输入与精度控制。

Item ID List Price Amount Unit Cost Attribute Status

运算列 unitcost 的值将由 listprice 与 amount 相乘得出。通过 editor 属性指定编辑类型,确保输入框仅接受数字并保留指定小数位。

点击行触发编辑状态

当用户点击表格中的某一行时,需要结束上一行的编辑状态,并开启当前行的编辑模式。通过 onClickRow 事件实现行切换逻辑:

var lastIndex;
$('#tt').datagrid({
    onClickRow: function(rowIndex) {
        if (lastIndex != rowIndex) {
            $('#tt').datagrid('endEdit', lastIndex);
            $('#tt').datagrid('beginEdit', rowIndex);
            setEditing(rowIndex);
        }
        lastIndex = rowIndex;
    }
});

变量 lastIndex 用于记录上一次编辑的行索引。切换行时调用 endEdit 保存数据,并通过 beginEdit 激活新行的编辑器,随后调用 setEditing 函数绑定运算逻辑。

绑定事件实现列运算

在 setEditing 函数中,获取当前行的所有编辑器实例,并为单价和数量输入框绑定 change 事件。当任一值发生变化时,自动计算总价并更新到目标编辑器中。

function setEditing(rowIndex) {
    var editors = $('#tt').datagrid('getEditors', rowIndex);
    var priceEditor = editors[0];
    var amountEditor = editors[1];
    var costEditor = editors[2];

    priceEditor.target.bind('change', function() {
        calculate();
    });
    amountEditor.target.bind('change', function() {
        calculate();
    });

    function calculate() {
        var cost = priceEditor.target.val() * amountEditor.target.val();
        $(costEditor.target).numberbox('setValue', cost);
    }
}

通过 getEditors 方法获取当前行的编辑器数组,按列顺序索引对应字段。绑定 change 事件后,用户修改单价或数量时,calculate 函数会实时读取输入值并执行乘法运算,最终通过 numberbox('setValue') 将结果写入总价列。

jQuery EasyUI 数据网格列运算界面

该实现方式适用于需要实时计算的场景,如订单金额、库存统计等。注意确保输入值为有效数字,避免空值或非法字符导致计算异常。如需更复杂的运算逻辑,可在 calculate 函数中扩展条件判断或调用外部计算模块。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。