我正在尝试根据“正文”第一行(tr class =“ Statistics”)中的内容按列对表格进行排序。
该行中的每个“ td”都有两个“ div”,这些“ div”由类别标识,这些类别与排序下拉列表中各自选择的值相匹配。 (为方便起见,使用了颜色编码,如下图所示)
我用来激活排序功能的jquery如下:
jQuery(document).ready(function ($) {
$("#SortBy").on('change',function() {
var Column = $(".CompTable tr > td:nth-child(n):not(:first-child),.CompTable tr > th:nth-child(n):not(:first-child)");
Column.sort(function(a,b) {
a = $(a).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
b = $(b).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
return (a === 'NA')-(b === 'NA') || -(a>b)||+(a<b);
})
jQuery('.divResult').html(Column); // <-- Table nested inside 'div'
});
});
我相信问题出在我用来识别表中除第一列之外的每一列的这段代码:
var Column = $(".CompTable tr > td:nth-child(n):not(:first-child),.CompTable tr > th:nth-child(n):not(:first-child)");
请帮助我纠正上述代码。目前,当我选择排序选项时,表格消失了。 :/
下面是完整的工作代码供参考:
jQuery(document).ready(function ($) {
$("#SortBy").on('change',function() {
var Column = $(".CompTable tr > td:nth-child(n):not(:first-child),.CompTable tr > th:nth-child(n):not(:first-child)");
Column.sort(function(a,b) {
a = $(a).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
b = $(b).find("tr.Statistics > td:not(:first) div."+jQuery(this).find("option:selected").val());
return (a === 'NA')-(b === 'NA') || -(a>b)||+(a<b);
})
jQuery('.divResult').html(Column);
});
});
.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/3.2.0/jquery.min.js"></script>
<div id="SortByDiv">
Sort by:
<select id="SortBy">
<option></option>
<option value=Battery style="color: blue">Battery</option>
<option value=ScreenSize style="color: red">ScreenSize</option>
</select>
</br></br></br>
<div class="divResult">
<table class="CompTable">
<thead>
<th> </th>
<th>Samsung</th>
<th>Apple</th>
<th>Motorola</th>
</thead>
<tbody>
<tr class="Statistics">
<td>Statistics</td>
<td>
<div style="display:flex; flex-flow:column-wrap; width: 100%;">
<div class="Battery" style="display:flex; color:blue; width: 100%;">3200</div>
<div class="ScreenSize" style="display:flex; color:red; width: 100%;">1024</div>
</div>
</td>
<td>
<div style="display:flex; flex-flow:column-wrap; width: 100%;">
<div class="Battery" style="display:flex; color:blue; width: 100%;">NA</div>
<div class="ScreenSize" style="display:flex; color:red; width: 100%;">1900</div>
</div>
</td>
<td>
<div style="display:flex; flex-flow:column-wrap; width: 100%;">
<div class="Battery" style="display:flex; color:blue; width: 100%;">4100</div>
<div class="ScreenSize" style="display:flex; color:red; width: 100%;">1500</div>
</div>
</td>
</tr>
<tr class="Color">
<td>Color</td>
<td>Blue</td>
<td>Red</td>
<td>Black</td>
</tr>
</tbody>
</table>
</div>
编辑:更正了以下注释中指出的jQuery表类名“ CompTable”中的错误。