javascript - 如何根据标题对许多表重新排序?
问题描述
我想根据它们各自的标题按字母顺序对许多表进行重新排序。
例子 :
目前,我有:
带有“PHP”标题的表格
带有“Javascript”标题的表格
带有“Android”标题的表格
我想看看:
带有“Android”标题的表格
带有“Javascript”标题的表格
带有“PHP”标题的表格
我不知道该怎么做。
这是我的代码:
$('table').each(function() {
$caption = $(this).find('>caption');
$table = $(this);
$table.sort(function (a, b) {
var $a = $(a),
$b = $(b),
aVal = $a.find(">caption").text().toLowerCase(),
bVal = $a.find(">caption").text().toLowerCase();
if (aVal < bVal) return -1;
else if (aVal > bVal) return 1;
else return 0;
});
$('#results').append($table);
});
解决方案
在迭代它们时无法对表进行排序。
首先,您可以获得每个表格的标题,然后将其与其对应的表格分组并将其推入一个数组中。现在对数组进行排序并显示内容。
var tables = [];
$('table').each(function() {
var caption = $(this).find('caption')[0];
tables.push({
'table' : $(this),
'caption': $(caption).text().toLowerCase()
});
});
tables.sort(function (tableA, tableB){
if (tableA.caption < tableB.caption){
return -1;
}
if (tableA.caption > tableB.caption){
return 1;
}
return 0;
});
$.each( tables, function( index, tableObject){
$('#results').append(tableObject.table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <caption>Zhp</caption> </table>
<table> <caption>php</caption> </table>
<table> <caption>Javascript</caption> </table>
<div id="results"></div>
推荐阅读
- excel - 将数据 Excel 导出到 Access 超过 1 行
- python - Python subprocess.Popen 带有变量设置
- linux - 如何从服务器 SCP 选定的文件
- r - 使用 ggplot2 + linerange() 根据单独的列向每一行添加点
- facebook - Facebook Graph API - 组 - 空数据
- json - 有效加载 8gb 腌制文件
- node.js - expressjs不在浏览器上呈现计算的html字符串
- javascript - 如何按类捕获元素并单击它?
- python - 在 Django Rest Framework 视图中映射 1 - many 关系
- python - 使用 Python(html2text,textile)将 HTML 转换为 Ascii 并返回的问题