是否可以在数据表构建行时附加点击事件?而不需要调用外部全局函数并查找 closes tr 并获取 DATA 对象?
$('#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',
}
});
我知道上面的例子不起作用,cos渲染函数必须返回字符串,它只是我需要的一个例子。
- 创建一个元素。
- 附加传递“row”对象的点击函数,而不调用全局函数。
最佳答案
简短的回答,不,你不能。我发现您不想想要,但我会使用类和事件委托(delegate),如下所示:
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);
});
<小时/>
技术上您可以使用 rowCallback
function在渲染每一行后附加处理程序,但您必须使用 .find()
或类似的方法才能返回到按钮,恕我直言,上面概述的方法要干净得多。
关于jquery - JavaScript - jquery DataTable 将按钮附加到行 + 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39376118/