我已经了解了 jQuery 数据表插件中的列排序以及控制它的各种方法。我有一个查询是否可以通过单击上箭头图标将按升序和下箭头图标进行排序的方式控制排序会按降序排序吗?
有两种方法可以做到这一点,具体取决于datatables
版本。
编辑数据表版本 1.9 或更低版本
你需要使用fnHeaderCallback http://legacy.datatables.net/usage/callbacks。通过此回调,您可以编辑每个th
表头中的元素。
我已经为您创建了一个工作示例。
直播:http://live.datatables.net/oduzov http://live.datatables.net/oduzov罢工>
代码:http://live.datatables.net/oduzov/edit#javascript,html http://live.datatables.net/oduzov/edit#javascript,html罢工>
这是背后的代码(打开代码片段以查看代码):
$(document).ready(function($) {
var table = $('#example').dataTable({
"fnHeaderCallback": function(nHead, aData, iStart, iEnd, aiDisplay) {
// do this only once
if ($(nHead).children("th").children("button").length === 0) {
// button asc, but you can put img or something else insted
var ascButton = $(document.createElement("button"))
.text("asc");
var descButton = $(document.createElement("button"))
.text("desc"); //
ascButton.click(function(event) {
var thElement = $(this).parent("th"); // parent TH element
var columnIndex = thElement.parent().children("th").index(thElement); // index of parent TH element in header
table.fnSort([
[columnIndex, 'asc']
]); // sort call
return false;
});
descButton.click(function(event) {
var thElement = $(this).parent("th");
var columnIndex = thElement.parent().children("th").index(thElement);
table.fnSort([
[columnIndex, 'desc']
]);
return false;
});
$(nHead).children("th").append(ascButton, descButton);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://legacy.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Director</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
</tbody>
</table>
对于数据表版本 1.10 及更高版本
回调有一个新名称,只是headerCallback http://datatables.net/reference/option/headerCallback。其他一切都是一样的,所以使用新的回调代替旧的 api。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)