我们正在使用DataTables jQuery插件(http://www.datatables.net)创建可排序的表。该插件自动检测每一列中数据的数据类型。
如果您想自己指定列的数据类型,则在初始化数据表时添加“aoColumns”属性:
$('#accountTable').dataTable({
"bPaginate": false,
"sScrollX": "100%",
"bScrollCollapse": true,
"aoColumns": [
null,
null,
{ "sType": "currency" },
{ "sType": "currency" }
]
});
注意,我下载了用于数据表的货币数据类型插件。这很好。
但是,我担心如果我们对表列进行更改,我们将忘记返回JS并更改在该表上初始化datatables插件的方式。
所以...最好根据需要直接在表中指定数据类型:
<table class="dataTables display">
<thead>
<tr>
<th>Category</th>
<th>Product</th>
<th sType="currency">Cost</th>
<th sType="currency">Retail</th>
...
有什么方法可以执行此操作,或者使用DataTables的默认功能(我找不到),或者使用JS循环,或者通过某种方式循环遍历表的标签并更新存在“sType”属性的sType?
最佳答案
这是一种绝对很酷的方法:
您的 header HTML:
<table id="sorted-table">
<thead>
<tr>
<th data-s-type="string">Number</th>
<th data-s-type="html">Complex Name</th>
<th>Price</th>
<th data-b-sortable="false">Action</th>
</tr>
</thead>
...
您的JS:
$('#sorted-table').dataTable({
...
"aoColumns": $('#sorted-table').find('thead tr th').map(function(){return $(this).data()})
});
注意:需要在数据属性中使用破折号。 jQuery将它们转换为 camelCase 形式,使其与数据表API兼容。
关于javascript - 使用<th>属性为DataTables指定列数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15574745/