解决jQuery Tablesorter无法按单元格图标列排序的问题
解决Tablesorter无法对含FontAwesome勾选图标的列排序问题
问题原因
Tablesorter默认解析器无法识别仅包含图标标签(或空内容)的单元格排序逻辑,需要自定义解析规则,或者为单元格添加可被解析的排序值。
方案一:自定义解析器(推荐,无需修改HTML结构)
先定义一个自定义解析器,将含勾选图标的单元格标记为1,空单元格标记为0,按数值排序:
// 自定义解析器:识别单元格是否包含FontAwesome勾选图标 $.tablesorter.addParser({ id: 'hasCheckIcon', is: function(s) { // 关闭自动检测,手动指定列使用该解析器 return false; }, format: function(s, table, cell) { // 判断单元格内是否存在.fa-check元素 return $(cell).find('.fa-check').length > 0 ? 1 : 0; }, type: 'numeric' // 按数值类型排序 }); // 初始化Tablesorter时指定列使用该解析器 $(function() { $('#serviceTable').tablesorter({ theme: 'metro-dark', showProcessing: true, headerTemplate: '{content} {icon}', widgets: ["uitheme", "filter", "zebra", "scroller"], // 为第4列(Billable,索引从0开始为3)指定自定义解析器 headers: { 3: { sorter: 'hasCheckIcon' } }, widgetOptions: { scroller_height: 1000, zebra: ["even", "odd"], filter_reset: ".reset", filter_cssFilter: "form-control input-sm", scroller_upAfterSort: true, scroller_jumpToHeader: true, scroller_rowHighlight: "hover", scroller_barWidth: null } }); });
方案二:添加隐藏排序值(无需修改JS逻辑)
在HTML单元格中添加隐藏的数值,让Tablesorter默认解析器能读取到排序依据:
<tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td><span style="display:none">1</span><i class="fa-solid fa-check"></i></td> </tr> <tr> <td>5</td> <td>6</td> <td>7</td> <td><span style="display:none">0</span></td> </tr> <tr> <td>5</td> <td>9</td> <td>2</td> <td><span style="display:none">1</span><i class="fa-solid fa-check"></i></td> </tr> <tr> <td>1</td> <td>1</td> <td>1</td> <td><span style="display:none">0</span></td> </tr> </tbody>
内容的提问来源于stack exchange,提问作者bart2puck
相关产品推荐
相关产品推荐

