[英]Add extra column to existing table populated with datatables
I am populating a table with datatables.我正在用数据表填充一个表。 The table has four columns always.
该表始终有四列。 But I need to add another column which can be shown or hidden based on boolean value.
但我需要添加另一列,可以根据 boolean 值显示或隐藏。 My code so far:
到目前为止我的代码:
{% show_extra_fields_button = show_extra_fields_bool %}
<table class="display" id="fields_datatable" class="fields_datatable">
<thead>
<tr>
<th>Name</th>
<th>Place</th>
<th>Email</th>
<th>Phone</th>
<th>Add Extra</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="/static/js/vendor/datatables.min.js"></script>
<script>
$(document).ready(function() {
$("#fields_datatable").dataTable({
ajax: {
"processing": true,
"dataSrc": "",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
]
})
if (show_extra_fields_button) {
$("#fields_datatable tr").each(function(){
$(this).append("<td><button>Add Extra</button</td>");
});
}
});
</script>
Here I would want to show the Add Extra
column based on the boolean value.在这里,我想显示基于 boolean 值的
Add Extra
列。 I want the header and the column values which will be buttons to be added using js.我想要 header 和将使用 js 添加按钮的列值。 How can I do that?
我怎样才能做到这一点?
You can use data tables built-in functionality.您可以使用数据表的内置功能。
To add a button column you can use the following column definition:要添加按钮列,您可以使用以下列定义:
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
Then use initComplete callback to set the columns' visibility once table has fully been initialised, data loaded and drawn:然后在表完全初始化、数据加载和绘制后使用initComplete回调设置列的可见性:
$("#fields_datatable").dataTable({
ajax: {
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
],
"initComplete": function (settings, json) {
// get instance of datatable
table = settings.oInstance.api();
// get column using its name and set visibility
table.column('buttonColumn:name').visible(show_extra_fields_button);
}
});
You can put -
instead of deleting that <td>
for example <td>-</td>
您可以放置
-
而不是删除该<td>
例如<td>-</td>
You can add to the table header just the same way you are adding to the table body.您可以添加到表 header 中,就像添加到表体中一样。
if (show_extra_fields_button) {
$('#fields_datatable thead tr').append('<th>Add Extra</th>')
}
Execute it just one time.只执行一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.