问题描述
我用 dataTable 和 tabledit 用循环创建 X 表,主要示例我从 https://www.webslesson.info/2020/05/make-editable-datatable-using-jquery-tabledit-plugin-with-php-ajax.html
情况是针对每个循环,tabledit 正在添加来自最新列 + 按钮(图像)的信息
并且对于每个循环,数据数量较少(循环大小) 如何解决这个问题?
这是代码:(其他PHPs与链接相同) 另外,如何为每个表格添加行按钮?
main.js:
$(document).ready(function(){
html ="";
for(x = 0; x < 5; x++) {
html += '<table id="" class="tabla table table-bordered table-striped">';
html += '<thead>';
html += ' <tr>';
html += ' <th>ID</th>';
html += ' <th>First Name</th>';
html += ' <th>Last Name</th>';
html += ' <th>Gender</th>';
html += ' </tr>';
html += '</thead>';
html += '<tbody></tbody>';
html += '</table>';
}
$('#tab').append(html);
//TRAE LOS DATOS DE LA BD
var dataTable = $('.tabla').DataTable({
"processing" : true,"serverSide" : true,"order" : [],"ajax" : {
url:"fetch.PHP",type:"POST"
}
});
// i did this,but doest work:
$addRowButton.on('click',function() {
console.log('clicked');
$dataTable.row.add([
counter +'.1',counter +'.2',counter +'.3',counter +'.4',counter +'.5'
] ).draw( false );
counter++;
});
// AGREGA Y EJECUTA BOTOnes DE EDITAR,BORRAR
$('.tabla').on('draw.dt',function(){
$('.tabla').tabledit({
url:'action.PHP',dataType:'json',columns:{
identifier : [0,'id'],editable:[[1,'first_name'],[2,'last_name'],[3,'gender','{"1":"Male","2":"Female"}']]
},restoreButton:false,onSuccess:function(data,textStatus,jqXHR)
{
if(data.action == 'delete')
{
$('#' + data.id).remove();
$('.tabla').DataTable().ajax.reload();
}
}
});
});
});
index.PHP:
<div id="tab" class="table-responsive">
</div>
解决方法
您可以使用 each
遍历表并分别初始化每个表。
类似于:
$(document).ready(function() {
html = "";
for (x = 0; x < 5; x++) {
html += '<table id="" class="tabla table table-bordered table-striped">';
html += '<thead>';
html += ' <tr>';
html += ' <th>ID</th>';
html += ' <th>First Name</th>';
html += ' <th>Last Name</th>';
html += ' <th>Gender</th>';
html += ' </tr>';
html += '</thead>';
html += '<tbody></tbody>';
html += '</table>';
html += '<button>Add row</button>';
}
$('#tab').append(html);
//TRAE LOS DATOS DE LA BD
$('.tabla').each(function() {
var $table = $(this);
var $addRowButton = $table.next();
var dataTable = $table.DataTable({
"processing": true,"serverSide": true,"order": [],"ajax": {
url: "fetch.php",type: "POST"
}
});
$addRowButton.on('click',function() {
$table.row.add([/*add_new_data_here*/]);
});
// AGREGA Y EJECUTA BOTONES DE EDITAR,BORRAR
$table.on('draw.dt',function() {
$table.Tabledit({
url: 'action.php',dataType: 'json',columns: {
identifier: [0,'id'],editable: [
[1,'first_name'],[2,'last_name'],[3,'gender','{"1":"Male","2":"Female"}']
]
},restoreButton: false,onSuccess: function(data,textStatus,jqXHR) {
if (data.action == 'delete') {
$('#' + data.id).remove();
$('.tabla').DataTable().ajax.reload();
}
}
});
});
});
});