[英]DataTables columns, columnDefs and rowCallback HTML5 initialisation
我目前有一個數據表(1.10.18版),其中裝有js的多個選項,但我需要使代碼更可重用,並且嘗試使用html5 data- *屬性初始化數據表。
<table id="dataTable" cellspacing="0" width="100%" data-source="ajax.mysource.php">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th><i class="fas fa-low-vision"></i></th>
</tr>
</thead>
</table>
我的jQuery代碼如下所示:
var dataTable = $('#dataTable').DataTable({
processing: true,
serverSide: true,
ajax: $('#dataTable').data('source'),
columns: [
{ 'data': 'name' },
{ 'data': 'address' },
{ 'data': 'visible' }
],
order: [[ 1, 'asc' ], [ 0, 'asc' ]],
responsive: true,
nowrap: true,
pageLength: 15,
lengthChange: false,
select: 'single',
columnDefs: [
{ targets: 0, width: "110px" },
{ targets: 1, width: "150px" },
{ targets: 1, render: $.fn.dataTable.render.ellipsis(80) },
{ targets: 2, render: $.fn.dataTable.render.visibilityIcon() }
],
rowCallback: function(row, data, index) {
if (data.visible == "0") {
$(row).addClass("notVisible");
}
}
});
我會為每個數據表使用一些共同點,但是如果我可以使用html5 data- *屬性直接在html中設置column,columnDefs和rowCallBack,那就太好了,這樣我就可以對不同的表使用相同的代碼,喜歡:
<th data-columns="address" data-column-defs="{targets: 1, width:'150px'}" data-row-callback="function...">Address</th>
除了排序,排序和頁面長度之外,我什么都沒有找到如何使用html5- *屬性的方法。
使用datatables.js實際上可以使用html5設置此選項嗎?
首先,您需要此處所述的1.10.5版本
從v1.10.5開始,DataTables還可以使用從HTML5 data- *屬性讀取的初始化選項
然后,您必須將數據屬性放到表元素而不是列元素。
<table id="example"
data-column-defs='[{"targets": 0, "width": "200px"}]'
data-page-length='2'
data-class="dataTable"
data-order='[[ 1, "asc" ]]'
data-columns='[{"data": "name"}, {"data": "position"}]'
>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Start Date</th>
<th>office</th>
</tr>
</thead>
</table>
這是您的完整摘要
var data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "$3,120", "start_date": "2011/04/25", "office": "Edinburgh" }, { "name": "Garrett Winters", "position": "Director", "salary": "$5,300", "start_date": "2011/07/25", "office": "Edinburgh" }, { "name": "Jane Doe", "position": "SW Architect", "salary": "$5,300", "start_date": "2011/07/25", "office": "Edinburgh" }, { "name": "John Doe", "position": "SW Developer", "salary": "$5,300", "start_date": "2011/07/25", "office": "Edinburgh" } ]; var oTable = $('#example').dataTable({ data: data });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/> <script src="https://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script> <table id="example" data-column-defs='[{"targets": 0, "width": "200px"}]' data-page-length='2' data-class="dataTable" data-order='[[ 1, "asc" ]]' data-columns='[{"data": "name"}, {"data": "position"}]' > <thead> <tr> <th>Name</th> <th>Position</th> <th>Salary</th> <th>Start Date</th> <th>office</th> </tr> </thead> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.