javascript - 识别在表格内单击了哪个按钮

标签 javascript jquery datatables

所以我有一个数据表,在每一行中我放置了三个按钮:

{
    "render": function(data, type, row, meta) {
        str = '<button id="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
            '<button id="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
            '<button  title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';

        return str;
    }
}

我像这样处理每个点击事件:

$('#spot_reports_tbl').off('click').on('click', '.action', function(e) {
    var id = $(this).attr('data-value');
    console.log('Target: ' + e.target.id);
    switch (e.target.id) {
        case 'view':
            //view_spotreport(id);
            break;
        case 'edit':
            //edit_spot_report(id);
            break;
        default:
            alert('Cannot handle event. Contact IT Admini');
    }

});

问题是,有时能成功获取到ID,有时却无法获取到。为什么会这样?

谢谢!

最佳答案

使用data-*属性而不是id。

{
    "render": function(data, type, row, meta) {
        str = '<button data-action="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
            '<button data-action="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
            '<button  title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';

        return str;
    }
}

事件处理:

$(document).on('click', '.action', function(e) {
    var action = $(this).data('action'); // Get action data attribute value

    switch (action) {
        case 'view':
            //view_spotreport(id);
            break;
        case 'edit':
            //edit_spot_report(id);
            break;
        default:
            alert('Cannot handle event. Contact IT Admini');
    }

});

关于javascript - 识别在表格内单击了哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31295077/

相关文章:

javascript - 运行测试用例后清理智能合约存储

jquery - HTML/CSS : display table-cell not centering text in firefox

javascript - html代码中div标签的错误消息

php - 类型错误 : oColumn is undefined When Using jQuery Datatables Library

javascript - 为 DataTables aoColumnDefs 创建 JavaScript 数组(JSON 格式)

JavaScript Array.filter 没有按预期工作

javascript - 带有长标签渲染问题的 flot 饼图

javascript - 删除多边形的顶点谷歌地图API v3

javascript - 如何将 jquery 类型导入到 typescript

javascript - jquery dataTables - 如何添加编辑和删除选项