我已经了解了 jQuery 数据表插件中的列排序以及控制它的各种方法。我有一个查询是否可以通过单击上方箭头图标将按升序排序的方式控制排序&向下箭头图标将按降序排序?
最佳答案
有两种方法可以做到这一点,具体取决于 datatables
版本。
编辑数据表版本 1.9 或更低版本
您需要使用 fnHeaderCallback
。通过此回调,您可以编辑每个 th
表头中的元素。
我已经为您创建了一个工作示例。 直播:<罢工>http://live.datatables.net/oduzov 罢工> 代码:<罢工>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
。其他一切都是一样的,所以使用新的回调代替旧的 api。
关于jquery - jQuery 数据表中的列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206894/