JavaScript - jquery DataTable 将按钮附加到行 + 单击事件

987*_*800 3 jquery datatables

是否可以在数据表构建行时附加点击事件?,无需调用外部全局函数并找到关闭的 tr 并获取数据对象?。

$('#example').DataTable({
     columns : [{
        title   : 'msg',
        sClass  : 'col-sm-2',
        render  : function(data, type, row){
            var b = $('<button>the button</button>').click(function(){
                alert(row.msg);
            })
            return b;
        }
     }],
     ajax:{
        type : 'POST',
        url  : 'foo.php',
     }
});
Run Code Online (Sandbox Code Playgroud)

我知道上面的例子不起作用,cos 渲染函数必须返回字符串,它只是我需要的一个例子。

  • 创建一个元素。
  • 附加单击函数传递“行”对象,而不调用全局函数。

Del*_*D0D 8

简短的回答,不,你不能。我看到你不想,但我会使用类和事件委托,如下所示:

var myDataTable=$('#example').DataTable({  // note the stored reference to the dataTable
     columns : [{
        title   : 'msg',
        sClass  : 'col-sm-2',
        render  : function(data, type, row){ 
            return '<button class="some-class">the button</button>';
        }
     }],
     ajax:{
        type : 'POST',
        url  : 'foo.php',
     }
});


$(document).on('click', '.some-class', function(){ 
        var $btn=$(this);
        var $tr=$btn.closest('tr');
        var dataTableRow=myDataTable.row($tr[0]); // get the DT row so we can use the API on it
        var rowData=dataTableRow.data();
        console.log(rowData.msg);
});
Run Code Online (Sandbox Code Playgroud)

从技术上讲,您可以使用该rowCallback函数在呈现每一行后附加处理程序,但您必须使用.find()或类似的方法才能返回按钮,并且上面概述的方法更简洁,恕我直言。