簡體   English   中英

如何在 HTML 表中進行自定義“排序依據”?

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

我是 Stackoverflow 的新手,我來到這里需要一些幫助,這個社區真的幫助我作為初學者編程東西,我仍然是一個!

我想知道如何按自定義順序對表格進行排序,例如此站點:

圖片1

圖片2

我之所以喜歡那個網站,是因為我也在制作英雄聯盟表,但只有角色和排名!

這是一個很好的例子!

這樣做(它已經很好地評論了):

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;
    }
  }
}

基本上根據它們的值切換表的兩行,直到一切都完成。

此外,是一個很棒的 stackoverflow 答案,提供了一個全面的好答案!

您可以使用 JavaScript 或使用這樣的插件從頭開始編寫代碼: https://datatables.net/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM