用随机值对表进行排序

时间:2019-11-07 20:43:54

标签: javascript html sorting

我是javascript / HTML的新手,我在Tabe中有要排序的值。问题是我如何使列/行循环,以便它们可以保持相同的数字。

<html>
<head>
<script>
function Table() {
  var list, i, switching, b, shouldSwitch, attrib;
  list = document.getElementById("picks");
  attrib = document.getElementsByTagName("TD");
  switching = true;
   while (switching) {

    switching = false;
    b = list.getElementsByTagName("p");
    for (i = 0; i < (b.length - 1); i++) {

      shouldSwitch = false;
          if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
               shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
        attrib[i].parentNode.insertBefore(attrib[i + 1], attrib[i]);
              switching = true;
}
}
}
</script>
</head>
<body>


<button onclick="Table()">Sort</button>

<table id="picks">
    <tr>
        <td><p>Sam</p></td>
        <td><p>Leo</p></td>
        <td><p>Teo</p></td>
    </tr>
    <tr>
        <td><p>Ann</p></td>
        <td><p>Susan</p></td>
        <td><p>Sasha</p></td>
    </tr>
    <tr>
        <td><p>Yu</p></td>
        <td><p>Harry</p></td>
        <td><p>Katy</p></td>
    </tr>
</table>



</body>
</html>

我尝试为document.getElementsByTagName(“ TR”);创建一个for循环。并没有真正达到最终结果。 林使用一列作为参数,并重新排列整个桌布。

1 个答案:

答案 0 :(得分:0)

您应该将数据存储在数组中,对其进行排序并从数组中显示它们。

使用JQuery将使DOM操作更加容易。

查看已接受的答案: Print out Javascript array in table