所以我有一个DataTable,在每行中我放了三个按钮:
{
"render": function(data, type, row, meta) {
str = '<button id="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
'<button id="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
'<button title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';
return str;
}
}
我处理每个点击事件:
$('#spot_reports_tbl').off('click').on('click', '.action', function(e) {
var id = $(this).attr('data-value');
console.log('Target: ' + e.target.id);
switch (e.target.id) {
case 'view':
//view_spotreport(id);
break;
case 'edit':
//edit_spot_report(id);
break;
default:
alert('Cannot handle event. Contact IT Admini');
}
});
问题是,有时它会成功获取ID,有时却无法获得它。为什么会这样?
谢谢!
答案 0 :(得分:2)
使用data-*
属性而不是id。
{
"render": function(data, type, row, meta) {
str = '<button data-action="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
'<button data-action="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
'<button title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';
return str;
}
}
事件处理:
$(document).on('click', '.action', function(e) {
var action = $(this).data('action'); // Get action data attribute value
switch (action) {
case 'view':
//view_spotreport(id);
break;
case 'edit':
//edit_spot_report(id);
break;
default:
alert('Cannot handle event. Contact IT Admini');
}
});