【发布时间】:2019-12-06 10:25:12
【问题描述】:
我想根据所选的行标题对表格列进行排序。我正在尝试调整以下小提琴(http://jsfiddle.net/fKMqD/)中使用的代码来解决这个问题:
该表有 2 行,行标题为“Ranking”和“Rating”。一个“排序依据”按钮,用于选择要排序的参数:
Sort by: <select id="SortBy">
<option></option>
<option>Ranking</option>
<option>Rating</option>
</select>
调用排序函数的jquery如下:
jQuery("#SortBy").on('change', function () {
var Rows = $('.CompTable > tr');
var RowtoSort = $(".CompTable > tr." + $(this).find("option:selected").text());
RowtoSort.find('td:not(:first)').sort(function(a, b) {
return a-b
}).each(function(new_Index) {
var original_Index = $(this).index();
'.CompTable > thead > tr > th'.each(function() {
var th = $(this).find('th:not(:first)');
console.log(th);
if (original_Index !== new_Index)
th.eq(original_Index).insertAfter(th.eq(new_Index));
});
'.compTable > tbody > tr > td'.each(function() {
var td = $(this).find('td:not(:first)');
console.log(td);
if (original_Index !== new_Index)
td.eq(original_Index).insertAfter(td.eq(new_Index));
});
});
return false;
});
});
但由于某种原因,表格列没有按预期进行排序。尝试了多种方式对其进行返工,但无济于事。
以下是我正在使用的完整代码:
jQuery(document).ready(function($) {
jQuery("#SortBy").on('change', function() {
var Rows = $('.CompTable > tr');
var RowtoSort = $(".CompTable > tr." + $(this).find("option:selected").text());
RowtoSort.find('td:not(:first)').sort(function(a, b) {
return a - b
}).each(function(new_Index) {
var original_Index = $(this).index();
'.CompTable > thead > tr > th'.each(function() {
var th = $(this).find('th:not(:first)');
console.log(th);
if (original_Index !== new_Index)
th.eq(original_Index).insertAfter(th.eq(new_Index));
});
'.compTable > tbody > tr > td'.each(function() {
var td = $(this).find('td:not(:first)');
console.log(td);
if (original_Index !== new_Index)
td.eq(original_Index).insertAfter(td.eq(new_Index));
});
});
return false;
});
});
.CompTable {
table-layout: fixed;
width: 50%;
position: relative;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
margin: 10px;
border: 1px solid #222;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Sort by:
<select id="SortBy">
<option></option>
<option>Ranking</option>
<option>Rating</option>
</select>
<table class="CompTable">
<thead>
<tr>
<th></th>
<th>Samsung</th>
<th>LG</th>
<th>Apple</th>
</tr>
</thead>
<tbody>
<tr class="Ranking">
<td>Ranking</td>
<td>3</td>
<td>2</td>
<td>1</td>
</tr>
<tr class="Rating">
<td>Rating</td>
<td>1.3</td>
<td>3.1</td>
<td>5.2</td>
</tr>
</tbody>
</table>
还可以找到相同的 js-fiddle:https://jsfiddle.net/mithunu/59d8gkry/
【问题讨论】:
标签: jquery sorting html-table