javascript - 在页面加载时按字母顺序对 html 表进行排序

标签 javascript jquery html sorting

我希望在页面加载时按字母顺序对 html 表格进行排序,就像对无序列表进行排序一样。

我尝试使用下面的代码但没有成功:

    var mylist = $('#myTable');
var listitems = mylist.children('tr').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

然后

<table id="myTable">
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/01/2016</td>
</tr>
</table>

我希望它按一行中第一列的字母顺序对表格进行排序。

我在网上找不到任何相关信息。

最佳答案

你的问题是这一行没有返回你的 trs:

var listitems = mylist.children('tr').get();

修改如下,一切正常。

var listitems = mylist.find('tr');

var mylist = $('#myTable');
var listitems = mylist.find('tr');
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/01/2016</td>
</tr>
</table>

关于javascript - 在页面加载时按字母顺序对 html 表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751453/

相关文章:

javascript - Leaflet.js - 创建标记并在 map 上显示弹出窗口

html - 对齐表格单元格底部的按钮

Javascript:如何加入所有链接(数组)

html - Webstorm 在 html 文件中给出奇怪的绿色背景

javascript - 如果高度超过 100px,改变位置

javascript - 为什么在 jQuery 中切换可拖动性的正确方法是?

javascript - 三个 JS - 找到网格与平面相交的所有点

javascript - Wavefront 文件到 WebGL 数组的转换在某处出错

jquery - jQuery 是否会使网页渲染速度减慢 100 毫秒或更多?

javascript - 使用适用于 IE 的 Ajax 进行文件发布