HTML table sort

前端 未结 5 1278
谎友^
谎友^ 2020-12-08 00:50

So basically I am running a mysql query that fetches data from my database and displays it in an easy to read layout for my users.

Name-----Address----Sales          


        
5条回答
  •  隐瞒了意图╮
    2020-12-08 01:50

    Flexbox-based tables can easily be sorted by using flexbox property "order".

    Here's an example:

    function sortTable() {
      let table = document.querySelector("#table")
      let children = [...table.children]
      let sortedArr = children.map(e => e.innerText).sort((a, b) => a.localeCompare(b));
    
      children.forEach(child => {
        child.style.order = sortedArr.indexOf(child.innerText)
      })
    }
    
    document.querySelector("#sort").addEventListener("click", sortTable)
    #table {
      display: flex;
      flex-direction: column
    }
    Melissa
    Justin
    Judy
    Skipper
    Alex

    Explanation

    The sortTable function extracts the data of the table into an array, which is then sorted in alphabetic order. After that we loop through the table items and assign the CSS property order equal to index of an item's data in our sorted array.

提交回复
热议问题