Javascript jquery数据表插件问题
我正在使用jquery数据表,并改编了以下示例Javascript jquery数据表插件问题,javascript,jquery,datatables,Javascript,Jquery,Datatables,我正在使用jquery数据表,并改编了以下示例 /* Formatting function for row details - modify as you need */ function format ( d ) { // `d` is the original data object for the row return '<table cellpadding="5" cellspacing="0" border="0" style="pad
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
//IMPORTANT PART
'<td>' + '<input type="text" id="inp">' + '</td>'+
'<td>' + '<button id="butt">' + 'click' + '</button>' + '</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
上面的id“butt”是一个按钮,它是行子级的一部分。换句话说,我希望操作行子级中的元素,而不是行本身。由于datatables将元素添加到DOM中,因此您必须使用委托进行选择,例如:
$('body').on('click', '#example tbody #butt', function () {
//do something
});
它不一定必须是body
,但您需要一个未动态添加到DOM中的元素,以便jQuery使用
此外,ID应该是唯一的,因此您不希望在每一行中添加具有相同ID的按钮。如果需要添加多个按钮,您需要使用一个类,绑定到该类的元素,然后处理每个按钮以获得适当的上下文。我可以在用于构造表的document.ready函数之外使用它吗?事件处理程序附加到body元素,只要主体元素被渲染,那么是的,它应该是好的——我相信它会好的。但是,实际上没有必要将事件绑定到document.ready函数的内部或外部-它应该以任何一种方式工作,而且最好将它放在内部。看见
$('body').on('click', '#example tbody #butt', function () {
//do something
});