简体   繁体   English

如何在 HTML 表中进行自定义“排序依据”?

[英]How do I make a custom 'sort by' in HTML Table?

I'm new on Stackoverflow, I came here needing some help, This community really helped me programming stuff as a beginner, And I still am one!我是 Stackoverflow 的新手,我来到这里需要一些帮助,这个社区真的帮助我作为初学者编程东西,我仍然是一个!

I wanted to know how can I sort table in a custom order such as this site:我想知道如何按自定义顺序对表格进行排序,例如此站点:

Image1图片1

Image2图片2

The reason why I want like that site because I'm making a league of legends table too but with only role and rank!我之所以喜欢那个网站,是因为我也在制作英雄联盟表,但只有角色和排名!

Here's a nice example of doing so! 这是一个很好的例子!

Do this (It's already commented really nicely):这样做(它已经很好地评论了):

function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      //check if the two rows should switch place:
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        //if so, mark as a switch and break the loop:
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}

Basically switch two rows of a table based on their value until everything's done.基本上根据它们的值切换表的两行,直到一切都完成。

Also, here 'sa great stackoverflow answer providing an all around good answer!此外,是一个很棒的 stackoverflow 答案,提供了一个全面的好答案!

You could code it from scratch using JavaScript or use a plugin like this: https://datatables.net/您可以使用 JavaScript 或使用这样的插件从头开始编写代码: https://datatables.net/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM