我有数据表使用服务器端处理返回数据。我没有修改数据表中给出的基本示例。
我有一些 bool 列,我想将其呈现为图标,例如1 = 绿色对勾 0 = 红叉或类似的东西。目前看起来像this . 我将如何只渲染 3 列?
这是代码,我已经尝试过了,但是这会导致整个表格都是空白的...
$(document).ready(function() {
$('#log').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "assetlog.php"
"columns": [
{ "data": "id" },
{ "data": "assetcode" },
{ "data": "name"},
{ "data": "shift" }
{ "data": "datetime" },
{ "data": "stop_production" },
{ "data": "furtheractions" }
{ "data": "jobcomplete" },
{ "data": "duration" },
],
"columnDefs": [
{
"render": function (data, type, row) {
return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
},
"targets": 6
}
]
} );
} );
谢谢
最佳答案
columns
和 columnDefs
是多余的;也就是说,您当前添加到 columnDefs
的内容应该只放入您的 columns
中,以获得您想要的刻度线。它应该看起来像这样:
/*Note that I'm assuming you're using DT 1.10.x, so the 'b' in front of boolean options
*is unnecessary, if you aren't using 1.10.x then go ahead and put those back in.*/
$(document).ready(function() {
$('#log').dataTable( {
"processing": true,
"serverSide": true,
"ajaxSource": "assetlog.php"
"columns": [
{ "data": "id" },
{ "data": "assetcode" },
{ "data": "name"},
{ "data": "shift" },
{ "data": "datetime" },
/*Note that data == true instead of ===, if you have 1 or 0 it isn't ===
(strictly equal) to true but it is == (evaluates to equal) to true*/
{ "data": "stop_production",
"render": function (data, type, row) {
return (data === true) ? '<span class="glyphicon glyphicon-ok">
</span>' : '<span class="glyphicon glyphicon-remove"></span>';}
},
{ "data": "furtheractions",
"render": function (data, type, row) {
return (data == true) ? '<span class="glyphicon glyphicon-ok">
</span>' : '<span class="glyphicon glyphicon-remove"></span>';}
},
{ "data": "jobcomplete",
"render": function (data, type, row) {
return (data == true) ? '<span class="glyphicon glyphicon-ok">
</span>' : '<span class="glyphicon glyphicon-remove"></span>';}
},
{ "data": "duration" }
]
} );
} );
我对您的代码进行了 3 处更改,其中 2 处与此问题相关,1 处仅更新语法。重要的 2 个变化是:
- 将
render
函数移动到您希望具有此行为的每一列中,而不是仅仅将其放在冗余的columnDefs
中 - 将
data === true
更改为data == true
因为 1 不是 === true 但它是 == true(=== 用于严格比较考虑类型)
一个不太相关的变化是:
bProcessing
andbServerSide
应该是processing
andserverSide
。前者是 DataTables 选项的旧格式,它使用匈牙利表示法,并且由于您没有columns
的匈牙利表示法,您必须使用 v1.10.x,它不需要该已弃用的表示法.
注意:您还提到在添加 columns
选项后您会得到一个空白页,但您似乎在 data: shift 之后缺少一个逗号
这可以解释这一点。
关于jquery - 呈现数据表 bool 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38245125/