可以在数据表构建行时附加单击事件吗?,无需调用外部全局函数并查找 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渲染函数必须返回字符串,它只是我需要的一个例子。
简短的回答,不,你不能。我发现您不想,但我会使用类和事件委托,如下所示:
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
函数在渲染每行后附加处理程序,但您必须使用
.find()
或类似的方法才能返回按钮,并且上面概述的方法要干净得多恕我直言。
$( '#example' ).DataTable( {
columns : [ {
data : 'msg',
title : 'msg',
sClass : 'col-sm-2',
createdCell : function( td, cellData, rowData, row, col ){
var b = $( '<button>the button</button>' ).click( function() {
alert( rowData.msg );
} );
$( td ).html( b );
}
} ],
// using data instead of ajax to demonstrate
data : [
{ msg : 'Message 1!' },
{ msg : 'Message 2!' },
{ msg : 'Message 3!' }
],
/*
ajax : {
type : 'POST',
url : 'foo.php',
}
*/
} );
只需将
b
传递给
$( td ).html()
即可!
if (dataTable.columns(colunIndex).search() !== e.value) {
dataTable.columns(colunIndex)
.search(e.value)
.draw();
$(this).blur();
$(this).focus();
}
let table = $('#table_patient_request').DataTable()
table.clear().draw();
const response = await [1,3,4,5,6,7]
const items = response.map( (resp,index) => {
const item = [
`<button type="button" id="exemplo_${index}" date-isconf="${resp.id}" class="btn btn-info waves-effect waves-light ml-1 mr-1">exemplo</button>`
]
table.row.add(item).draw()
table.on('click', `#exemplo_${index}`, function (e) {
alert('exemplo')
});
})