如何实现点击表格X列对Checkbox(选中/未选中)进行排序?
按Checkbox选中状态排序表格行的实现方案
需求说明
点击表格的「X」列表头,按行内Checkbox的选中/未选中状态对表格行进行排序,保留现有按Price排序的逻辑。
修改后的完整代码
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table" id="myTable"> <tr> <th onclick="sortPrice()">Price</th> <th>Stock</th> <th>%</th> <th onclick="sortCheckbox()">X</th> </tr> <tr class="item"> <td class="sortPrice">1</td> <td>1</td> <td>2</td> <td><input type="checkbox" value="1"></td> </tr> <tr class="item"> <td class="sortPrice">4</td> <td>3</td> <td>1</td> <td><input type="checkbox" value="2"></td> </tr> <tr class="item"> <td class="sortPrice">7</td> <td>4</td> <td>6</td> <td><input type="checkbox" value="3"></td> </tr> <tr class="item"> <td class="sortPrice">2</td> <td>7</td> <td>8</td> <td><input type="checkbox" value="4"></td> </tr> <tr class="item"> <td class="sortPrice">3</td> <td>4</td> <td>2</td> <td><input type="checkbox" value="5"></td> </tr> </table>
JavaScript代码
var sortedPrice = false; var sortedCheckbox = false; // 控制Checkbox排序的升降状态 function sortPrice() { $('#myTable').append( $('#myTable').find('tr.item').sort(function (a, b) { var td_a = $($(a).find('td.sortPrice')[0]); var td_b = $($(b).find('td.sortPrice')[0]); if(sortedPrice){ if(td_a.html() == 'Free') return -1; return td_b.html().replace(/\D/g, '') - td_a.html().replace(/\D/g, ''); }else{ if(td_a.html() == 'Free') return 1; return td_a.html().replace(/\D/g, '') - td_b.html().replace(/\D/g, ''); } }) ); sortedPrice = !sortedPrice; } function sortCheckbox() { $('#myTable').append( $('#myTable').find('tr.item').sort(function (a, b) { // 获取两行的Checkbox选中状态,选中为1,未选中为0 var checkboxA = $(a).find('input[type="checkbox"]')[0].checked ? 1 : 0; var checkboxB = $(b).find('input[type="checkbox"]')[0].checked ? 1 : 0; if(sortedCheckbox){ // 降序:未选中行在前,选中行在后 return checkboxA - checkboxB; }else{ // 升序:选中行在前,未选中行在后 return checkboxB - checkboxA; } }) ); sortedCheckbox = !sortedCheckbox; }
代码说明
- HTML修改:给「X」列表头的
th标签添加onclick="sortCheckbox()",绑定排序触发事件。 - 状态管理:新增
sortedCheckbox变量记录排序方向,初始为false(默认选中行排在前面)。 - 排序逻辑:
- 升序时:通过
checkboxB - checkboxA让选中状态(值为1)的行优先排列。 - 降序时:通过
checkboxA - checkboxB让未选中状态(值为0)的行优先排列。
- 升序时:通过
- 方向切换:每次排序完成后反转
sortedCheckbox的值,实现点击表头切换升降序。
内容的提问来源于stack exchange,提问作者Xylex
相关产品推荐
相关产品推荐

