Datatable column onClick

我们两清 提交于 2019-12-13 15:18:00

问题


I am referring the following Datatable example -

https://datatables.net/examples/api/select_single_row.html
The example captures onclick event on the entire row

$('#example tbody').on( 'click', 'tr', function (){}

I wish to capture an event on the click of a particular columns, say column Name, Position and Office. How do I do that?


回答1:


If you know the table colums index then you might you use this.

$('#example tbody').on( 'click', 'tr td:eq(0)', function (){
   alert("col1");
});
$('#example tbody').on( 'click', 'tr td:eq(1)', function (){
   alert("col2");
});
$('#example tbody').on( 'click', 'tr td:eq(4)', function (){
   alert("col5");
});



回答2:


You can access clicks in columns hooking and event handler in the elements you want in the fnRowCallback. Here is a complete example with a table with 2 extra columns showing an icon that receives the click:

$('#example').DataTable({
        dom: 'lfrt',
        paging: false,
        rowBorder: true,
        hover: true,
        serverSide: false,
        rowHeight: 30,
        order: [[ 1, 'asc' ]],
        columns: [
            {
                title: 'Id',
                visible: false,
                searchable: false
            },
            {
                title: 'version',
                visible: false,
                searchable: false
            }                {
                title: Name'
            },
            {
                data: null,
                title: 'Diagram',
                searchable: false,
                sortable: false,
                defaultContent: '<i class="fa fa fa-sitemap icon-btn" data-btnaction="grafo"></i>',
                className: 'text-center'
            },
            {
                data: null,
                title: 'History',
                searchable: false,
                sortable: false,
                defaultContent: '<i class="fa fa-history icon-btn" data-btnaction="appdetail"></i>',
                className: 'text-center'
            }

        ],
        select: false,
        fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
            $('td > i', nRow).on('click', function() {
                // if you have the property "data" in your columns, access via aData.property_name
                // if not, access data array from parameter aData, aData[0] = data for field 0, and so on...
                var btnAction = $(this).data('btnaction');
                if (btnAction === 'grafo'){
                } else if (btnAction === 'appdetail'){
                    // do something......
                }
            });
        }
    });


来源:https://stackoverflow.com/questions/36123337/datatable-column-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!