Html HTML表格排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10683712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:33:40  来源:igfitidea点击:

HTML table sort

htmlsorting

提问by h3tr1ck

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.

所以基本上我正在运行一个 mysql 查询,它从我的数据库中获取数据并以易于阅读的布局为我的用户显示它。

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

You get the gist. And now I want to let the user sort the html table by let's say sales person. How would I easily do that using a drop down menu?

你明白了。现在我想让用户通过让我们说销售人员对 html 表进行排序。我如何使用下拉菜单轻松做到这一点?

<div class='menu'>
  <ul>
    <li><a href='#'><span>Sales Person</span></a>
      <ul>
        <li><a href='#'><span>Melissa</span></a></li>
        <li><a href='#'><span>Justin</span></a></li>
        <li><a href='#'><span>Judy</span></a></li>
        <li><a href='#'><span>Skipper</span></a></li>
        <li><a href='#'><span>Alex</span></a></li>
      </ul>
    </li>
  </ul>
</div>

回答by verisimilitude

Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)

检查您是否可以使用下面提到的任何 JQuery 插件。简直太棒了,并提供了广泛的工作选择,并且集成起来更轻松。:)

https://github.com/paulopmx/Flexigrid- Flexgrid
http://datatables.net/index- Data tables.
https://github.com/tonytomov/jqGrid

https://github.com/paulopmx/Flexigrid- Flexgrid
http://datatables.net/index- 数据表。
https://github.com/tonytomov/jqGrid

If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.

如果没有,您需要有一个链接到那些调用服务器端脚本来调用排序的表头。

回答by Penny Liu

Another approach to sort HTML table. (based on W3.JS HTML Sort)

另一种对 HTML 表进行排序的方法。(基于W3.JS HTML Sort

let tid = "#usersTable";
let headers = document.querySelectorAll(tid + " th");

// Sort the table element when clicking on the table headers
headers.forEach(function(element, i) {
  element.addEventListener("click", function() {
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");
  });
});
th {
  cursor: pointer;
  background-color: coral;
}
<script src="https://www.w3schools.com/lib/w3.js"></script>
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>

<table id="usersTable" class="w3-table-all">
  <!--     
  <tr>
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>
  </tr> 
  -->
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:2911002</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:2201002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:2901092</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:2801002</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:2901009</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>

回答by Tom P

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

我在浏览器中对 HTML 表格进行排序的方式使用了简单、朴素的 Javascript。

The basic process is:

基本流程是:

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table
  1. 为每个表格标题添加一个点击处理程序
  2. 单击处理程序记录要排序的列的索引
  3. 表被转换为数组数组(行和单元格)
  4. 该数组使用 javascript 排序函数进行排序
  5. 排序数组中的数据被插入回 HTML 表中

The table should, of course, be nice HTML. Something like this...

当然,表格应该是漂亮的 HTML。像这样的东西...

<table>
 <thead>
  <tr><th>Name</th><th>Age</th></tr>
 </thead>
 <tbody>
  <tr><td>Sioned</td><td>62</td></tr>
  <tr><td>Dylan</td><td>37</td></tr>
  ...etc...
 </tbody>
</table>

So, first adding the click handlers...

所以,首先添加点击处理程序......

const table = document.querySelector('table'); //get the table to be sorted

table.querySelectorAll('th') // get all the table header elements
  .forEach((element, columnNo)=>{ // add a click handler for each 
    element.addEventListener('click', event => {
        sortTable(table, columnNo); //call a function which sorts the table by a given column number
    })
  })

This won't work right now because the sortTablefunction which is called in the event handler doesn't exist.

这现在sortTable不起作用,因为在事件处理程序中调用的函数不存在。

Lets write it...

来写吧...

function sortTable(table, sortColumn){
  // get the data from the table cells
  const tableBody = table.querySelector('tbody')
  const tableData = table2data(tableBody);
  // sort the extracted data
  tableData.sort((a, b)=>{
    if(a[sortColumn] > b[sortColumn]){
      return 1;
    }
    return -1;
  })
  // put the sorted data back into the table
  data2table(tableBody, tableData);
}

So now we get to the meat of the problem, we need to make the functions table2datato get data out of the table, and data2tableto put it back in once sorted.

所以现在我们进入了问题的核心,我们需要创建函数table2data来从表中获取数据,并data2table在排序后将其放回。

Here they are ...

他们来了 ...

// this function gets data from the rows and cells 
// within an html tbody element
function table2data(tableBody){
  const tableData = []; // create the array that'll hold the data rows
  tableBody.querySelectorAll('tr')
    .forEach(row=>{  // for each table row...
      const rowData = [];  // make an array for that row
      row.querySelectorAll('td')  // for each cell in that row
        .forEach(cell=>{
          rowData.push(cell.innerText);  // add it to the row data
        })
      tableData.push(rowData);  // add the full row to the table data 
    });
  return tableData;
}

// this function puts data into an html tbody element
function data2table(tableBody, tableData){
  tableBody.querySelectorAll('tr') // for each table row...
    .forEach((row, i)=>{  
      const rowData = tableData[i]; // get the array for the row data
      row.querySelectorAll('td')  // for each table cell ...
        .forEach((cell, j)=>{
          cell.innerText = rowData[j]; // put the appropriate array element into the cell
        })
      tableData.push(rowData);
    });
}

And that should do it.

那应该这样做。

A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2"is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.

您可能希望添加的一些内容(或您可能希望使用现成解决方案的原因): 更改排序方向和类型的选项,即您可能希望按数字对某些列进行排序("10" > "2"是错误的,因为它们是字符串,可能不是您想要的)。将列标记为已排序的能力。某种数据验证。

回答by smilyface

Here is another library.

这是另一个图书馆。

Changes required are -
1. Add sorttable js
2. Add class name sortableto table.

所需的更改是 -
1. 添加 sorttable js
2. 将类名添加sortable到表中。

<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
<table class="sortable">

Click the table headersto sort the table accordingly:

单击表格标题以相应地对表格进行排序:

<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:2911002</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:2201002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:2901092</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:2801002</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:2901009</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>

回答by Ivan Ivanov

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

使用 flexbox 属性“order”可以轻松地对基于 Flexbox 的表格进行排序。

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
}
<div id="table">
  <div>Melissa</div>
  <div>Justin</div>
  <div>Judy</div>
  <div>Skipper</div>
  <div>Alex</div>
</div>
<button id="sort"> sort </button>

Explanation

解释

The sortTablefunction 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 orderequal to index of an item's data in our sorted array.

sortTable函数将表中的数据提取到一个数组中,然后按字母顺序排序。之后,我们遍历表项并分配 CSS 属性order等于排序数组中项数据的索引。