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

如何在jqGrid列内的图标元素上实现onclick点击事件?

三种可行的实现方式,按需选择:

1. 直接在formatter中嵌入onclick属性

修改你现有的formatter代码,给<a>标签直接添加onclick属性,还能把当前行的ID或数据直接传入函数:

formatter: function (cellvalue, options, rowobject) {
    return '<div class="text-center email_production">' +
        '<a data-toggle="modal" data-target="#toMailModal" class="icon_color pr-2" onclick="handleEmailClick(' + options.rowId + ', ' + JSON.stringify(rowobject) + ')"><i class="fa fa-envelope"></i></a>' +
        '</div>';
}

// 在全局或合适的作用域定义处理函数
function handleEmailClick(rowId, rowData) {
    // 这里写你要触发的业务逻辑,比如根据行ID或数据做操作
    console.log('点击的行ID:', rowId);
    console.log('行数据:', rowData);
}

这种方式最直接,适合简单场景,能快速拿到当前行的信息。

2. 用事件委托绑定点击事件

由于jqGrid的行是动态渲染的,直接绑定事件可能失效,用事件委托更可靠,不需要修改formatter代码:

// 放在页面初始化代码中(比如$(function(){ ... })里)
$(document).on('click', '.email_production .icon_color', function(e) {
    // 阻止a标签默认跳转(如果需要)
    e.preventDefault();
    // 获取当前行ID
    var rowId = $(this).closest('tr').attr('id');
    // 通过jqGrid方法获取行数据
    var rowData = $('#你的表格ID').jqGrid('getRowData', rowId);
    // 执行你的业务逻辑
    console.log('点击的行数据:', rowData);
});

这种方式适合需要统一管理事件的场景,避免重复绑定。

3. 利用jqGrid的gridComplete事件

在jqGrid的配置项中添加gridComplete回调,等表格渲染完成后给图标绑定点击事件:

$("#你的表格ID").jqGrid({
    // 其他配置项...
    colModel: [
        // 带图标的列配置
        {
            name: 'emailCol',
            formatter: function (cellvalue, options, rowobject) {
                return '<div class="text-center email_production">' +
                    '<a data-toggle="modal" data-target="#toMailModal" class="icon_color pr-2"><i class="fa fa-envelope"></i></a>' +
                    '</div>';
            }
        }
    ],
    // 表格渲染完成后触发
    gridComplete: function() {
        // 先解绑再绑定,避免重复触发
        $('.email_production .icon_color').off('click').on('click', function() {
            var rowId = $(this).closest('tr').attr('id');
            var rowData = $('#你的表格ID').jqGrid('getRowData', rowId);
            // 执行自定义函数
            handleEmail(rowData);
        });
    }
});

// 定义处理函数
function handleEmail(data) {
    // 这里写业务逻辑
}

内容的提问来源于stack exchange,提问作者Baba Ranjith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:25:33