使用 JQuery 实现将 table 按照列排序
代码如下
<!DOCTYPE html>
<html>
<head>
<title>如何使用js使table按照表头排序</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div style="text-align: center;margin: 10px;">
<button type="button" style="width: 200px;" class="btn btn-outline-danger">按照表头排序</button>
</div>
<table class="table table-hover" style="width: 80%;text-align:center;margin: 0 auto;border: 0;" id="sorttable">
<thead class="thead-dark">
<tr>
<th>Fri</th>
<th>Thu</th>
<th>Wed</th>
<th>Tue</th>
<th>Mon</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
</tbody>
</table>
</body>
<script type="text/javascript">
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
jQuery.moveColumn = function(table, from, to) {
var rows = jQuery('tr', table);
var cols;
rows.each(function() {
cols = jQuery(this).children('th, td');
cols.eq(from).swapWith(cols.eq(to));
});
};
$(function() {
$("button").click(function() {
var tbl = $("#sorttable");
$('#sorttable tr').eq(0).each(function(i) { // 遍历 tr
var length = $(this).find('th').length;
for (var i = 0; i < length / 2; i++) {
jQuery.moveColumn(tbl, i, length - i - 1);
}
});
});
});
</script>
</html>
未排序前
排序后
参考资料