问题描述
我的jQuery DataTable中有编辑和删除按钮。第一列是记录ID列,并且已隐藏。
我有编辑和删除按钮的事件处理程序。
我应该使用DataTable click和tr函数的事件处理程序来获取ID,还是应该使用按钮事件处理程序(首选),如何从行中获取ID?也就是说,确定单击了哪一行?
I have Edit and Delete buttons in my jQuery DataTable. The first column is a record ID column and is hidden.I have event handlers for the Edit and Delete buttons.Should I rather use the event handler for the DataTable click and tr function to get the id, or if using the button event handlers (preferable), how can I get the Id from the row? i.e. identify which row was clicked on?
const dataTable = $('#personTable').DataTable({
data: serializedObject,
columns: [
{ data: 'ID', 'visible': false},
{ data: 'TitleCode' },
{ data: 'TitleDetail' },
{ data: 'FirstName' },
{ data: 'LastName' },
{data: null}
],
columnDefs: [
{
targets: 8,
data: 'ID', //'<div class="btn-group" style="width:70px"> <button type="button"' +
defaultContent: '<div class="floatRightClass" >' +
'<a class="btn btn-default glyphicon glyphicon-pencil btn-edit" title="Edit"> </a>' +
'<a class="btn btn-default glyphicon glyphicon-trash btn-delete" title="Delete"> </a>' +
'</div>'
},
]
});
$(".btn-delete").click(function (e)
{
var dtTable = $('#personTable').DataTable();
var selectedRows = dtTable.rows('tr.selected');
var id = selectedRows.data().toArray().map(function (row) { return row.id });
console.log("id= " + ID);
// or
console.log("id= " + dataTable.rows('tr.selected').data().toArray().map(function(row){return row.ID}));
// This works, but the row index is hardcoded
alert("..." + dtTable.cells({ row: 0, column: 0 }).data()[0]);
// Error: undefined
selectedIndex = dtTable.row(this).data()[0];
alert("Id = " + selectedIndex.ID);
});
$('#personTable tbody').on('click', '.btn-delete', function ()
{
var tr = $(this).closest("tr");
var rowindex = tr.index();
alert("rowindex " + rowindex);
// Get the value of the ID in the hidden column (col: 0)
alert("..." + dataTable.cells({ row: rowindex, column: 0 }).data()[0]);
});
推荐答案
我建议采用以下方法。
这里的必要部分是使用方法(您不需要具有要删除的记录的ID)。
Essential part here is to use rows().remove()
method (you don't need to have id's of the records you would like to delete).
但是,如果您也希望从后端存储中删除这些记录,则可以执行以下操作:
However, if you wish to delete those records from your backend storage as well, you might do something like:
$('#delete').on('click', function() {
const selectedRows = dataTable.rows('tr.selected');
$.ajax(/* throw selected rows data (or particular properties) using selectedRows.data() */);
selectedRows.remove().draw();
});
//source data
const srcData = [
{id: 1, name: 'Steve Rogers', title: 'Captain America'},
{id: 2, name: 'Anthony Stark', title: 'Iron Man'},
{id: 3, name: 'Peter Parker', title: 'Spider Man'},
{id: 4, name: 'Bruce Banner', title: 'Halk'},
{id: 5, name: 'Thor Odinsson', title: 'Thor'}
];
//data table initialization
const dataTable = $('#mytable').DataTable({
data: srcData,
dom: 't',
columns: [
{data: 'id', visible: false},
{data: 'name', title: 'Name'},
//append 'Edit'/'Delete' buttons to the rightmost edge of the cell
{data: 'title', title: 'Title', render: cellData => cellData+'<button class="delete">Delete</button><button class="edit">Edit</button>'}
]
});
//delete button handler
$('#mytable').on('click', '.delete', function () {
//grab parent <tr> node of the button, use it as
//a selector to throw its id into message and
//delete corresponding dataTable row
const currentRow = dataTable.row($(this).closest('tr'));
$('#msg').text(`Row id ${currentRow.data().id} (${currentRow.data().title}) was removed`);
currentRow.remove().draw();
});
//edit button handler
$('#mytable').on('click', '.edit', function(){
$(this).closest('tr').toggleClass('editing');
if($(this).closest('tr').hasClass('editing')) {
//turn each table cell into input field
[...$(this).closest('tr').find('td')].forEach(function(td, colindex){
$(td).html(`<input value="${dataTable.cell(td).data()}"></input> ${colindex==this.length-1?'<button class="delete">Delete</button><button class="edit">Edit</button>':''}`)
}, $(this).closest('tr').find('td'));
}
else {
//grab input fields from within each cell and
//put their values into corresponding dataTable cell
[...$(this).closest('tr').find('td')].forEach(function(td, colindex){
const cellValue = $(td).find('input').val();
dataTable.cell(td).data(cellValue);
$(td).html(`${cellValue}${colindex==this.length-1?'<button class="delete">Delete</button><button class="edit">Edit</button>':''}`);
}, $(this).closest('tr').find('td'));
dataTable.draw();
}
});
td button {
display: block;
float: right;
}
<!doctype html><html><head><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></head><body><table id="mytable"></table><div id="msg"></div></body></html>
这篇关于如何获取隐藏的ID以删除jQuery Datatable中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!