简体   繁体   English

使用javascript按具有高,中,低值的列对html表进行排序

[英]Sort html table by columns with high, medium, low values using javascript

I am trying to sort a table using javascript but not in the traditional numerical or alphabetical sort method.我正在尝试使用 javascript 对表格进行排序,但不使用传统的数字或字母排序方法。 Each Table row has 3 TD's.每个表行有 3 个 TD。 The first is the name second is a level (high, medium, low or blank) and the third is also a level (high, medium, low or blank).第一个是名称,第二个是级别(高、中、低或空白),第三个也是级别(高、中、低或空白)。 I am trying to sort the table based on the levels value , high, medium or low, and sending the empty TD's to the bottom.我正在尝试根据级别值、高、中或低对表格进行排序,并将空的 TD 发送到底部。

I normally work with PHP so I am a little weak when it comes to javascript.我通常使用 PHP,所以在 javascript 方面我有点弱。 Basics of what I am trying to do:我正在尝试做的基础知识:

Count the number of tr's exclude the first one (Because its the header) for each tr get the innerHTML of the second td.为每个 tr 计算 tr 的数量,排除第一个(因为它的标题)得到第二个 td 的 innerHTML。 Compare each tds innerHTML and arrange them from High to low putting the empty ones last.比较每个 tds innerHTML 并将它们从高到低排列,将空的放在最后。 If the header is clicked again reverse.如果再次单击标题反向。

I think i pretty much have it worked out but I get stuck when it comes to switching the elements order.我想我几乎已经解决了,但是在切换元素顺序时我陷入了困境。

<table id="myTable2">
<tr>
   <th>Food/Beverage</th> 
   <th onclick="sortTable(1)">Alkalizing Level</th>
   <th onclick="sortTable(2)">Acidic Level</th>
</tr>
<tr>
    <td>Ale (Dark)</td>
    <td></td>
    <td>High</td>
</tr>
<tr>
    <td>Ale (Pale)</td>
    <td></td>
    <td>High</td>
</tr>
<tr>
   <td>Alkaline, Ionized Water</td>
    <td>High</td>
   <td></td>
</tr>
<tr>
   <td>Almond Butter</td>
   <td>Medium</td>
   <td></td>
</tr>
<tr>
   <td>Almond Milk (unsweetened)</td>
   <td>Low</td>
   <td></td>
</tr>
<tr>
  <td>Almonds</td>
  <td>Medium</td>
  <td></td>
</tr>
<tr>
  <td>Amaranth Seeds</td>
  <td>Low</td>
  <td></td>
</tr>
<tr>
   <td>Apple Cider Vinegar</td>
   <td></td>
   <td>Low</td>
</tr>
<tr>
  <td>Apple Juice</td>
  <td></td>
  <td>High</td>
</tr>
<tr>
  <td>Apple Pie</td>
  <td></td>
  <td>High</td>
 </tr>
<tr>
  <td>Apples</td>
  <td></td>
  <td>Medium</td>
</tr>
<tr>
  <td>Apricots</td>
  <td></td>
  <td>Medium</td>
</tr>
<tr>
  <td>Apricots (Dried)</td>
  <td></td>
  <td>High</td>
  </tr>
</table>

JS JS

<script>
table = document.getElementById("myTable2");    
rows = table.rows;
i = 1;
count = 0;
while(i < rows.length){
alkLevel = rows[i].getElementsByTagName("TD")[1].innerHTML;
alkLevelNext = rows[i+1].getElementsByTagName("TD")[1].innerHTML;
var alkLevelPosition = 0;

i++;
if(alkLevel === "High"){
    alkLevelPosition += 1;

}
if (alkLevel === "Medium"){
    alkLevelPosition += 2;

    }
if(alkLevel === "Low"){
    alkLevelPosition += 3;

   }
if(alkLevel === ""){
    alkLevelPosition += 4;

   }



    if (alkLevelPosition > alkLevelNext) {

      //shouldSwitch = true;

      //break;
    }

 }
</script>

Here is an approach to getting the table sort you are looking for.这是一种获得您正在寻找的表格排序的方法。

Added click event listeners to the table headers (rather than the inline onclick approach), then determined which column controls the sort using cellIndex , and included a sort function that handles the high, medium, low scoring properly.向表标题添加了 click 事件侦听器(而不是内联onclick方法),然后使用cellIndex确定哪一列控制排序,并包含一个排序函数,可以正确处理高、中、低评分。

Each time a header is clicked, all the table rows (except the header row) are removed, sorted, and then appended in the new order (added thead and tbody elements to simplify the selections) - in addition a class indicating the direction of the sort is added to the corresponding header element so that the next sort can be reversed.每次单击标题时,所有表格行(标题行除外)都将被删除、排序,然后以新顺序附加(添加了theadtbody元素以简化选择)-此外还有一个指示方向的类sort 被添加到相应的标题元素,以便可以反转下一个排序。

Also, added alpha sort to the first table column as a bonus (just to simplify element selection and attaching the event listeners).此外,将 alpha 排序添加到第一个表列作为奖励(只是为了简化元素选择和附加事件侦听器)。

 const headings = document.querySelectorAll('#myTable th'); const tbody = document.querySelector('#myTable tbody'); const sortRows = (order, i) => { const rows = document.querySelectorAll('#myTable tbody tr'); if (i === 0) { if (order === 'asc') { return Array.from(rows).sort(); } else { return Array.from(rows).sort().reverse(); } } else { return Array.from(rows).sort((a, b) => { const aval = a.cells[i].textContent; const bval = b.cells[i].textContent; let s = 0; if (aval === bval) { s = 0; } else if (aval === 'High') { s = 1; } else if (bval === 'High') { s = -1; } else if (aval === 'Medium') { s = 1; } else if (bval === 'Medium') { s = -1; } else if (aval === 'Low') { s = 1; } else if (bval === 'Low') { s = -1; } if (order === 'desc') { s *= -1; } return s; }); } }; for (const heading of headings) { heading.addEventListener('click', (event) => { const fragment = document.createDocumentFragment(); const elem = event.currentTarget; let order = 'asc'; if (elem.classList.contains('asc')) { order = 'desc'; elem.classList.remove('asc'); elem.classList.add('desc'); } else { elem.classList.remove('desc'); elem.classList.add('asc'); } for (const s of sortRows(order, elem.cellIndex)) { fragment.appendChild(s); } while (tbody.firstChild) { tbody.removeChild(tbody.firstChild); } tbody.appendChild(fragment); }); }
 th:hover { cursor: pointer; }
 <table id="myTable"> <thead> <tr> <th>Food/Beverage</th> <th>Alkalizing Level</th> <th>Acidic Level</th> </tr> </thead> <tbody> <tr> <td>Ale (Dark)</td> <td></td> <td>High</td> </tr> <tr> <td>Ale (Pale)</td> <td></td> <td>High</td> </tr> <tr> <td>Alkaline, Ionized Water</td> <td>High</td> <td></td> </tr> <tr> <td>Almond Butter</td> <td>Medium</td> <td></td> </tr> <tr> <td>Almond Milk (unsweetened)</td> <td>Low</td> <td></td> </tr> <tr> <td>Almonds</td> <td>Medium</td> <td></td> </tr> <tr> <td>Amaranth Seeds</td> <td>Low</td> <td></td> </tr> <tr> <td>Apple Cider Vinegar</td> <td></td> <td>Low</td> </tr> <tr> <td>Apple Juice</td> <td></td> <td>High</td> </tr> <tr> <td>Apple Pie</td> <td></td> <td>High</td> </tr> <tr> <td>Apples</td> <td></td> <td>Medium</td> </tr> <tr> <td>Apricots</td> <td></td> <td>Medium</td> </tr> <tr> <td>Apricots (Dried)</td> <td></td> <td>High</td> </tr> </tbody> </table>

So it sounds like you just need some help interacting with the DOM (Document Object Model).所以听起来您只需要一些帮助与 DOM(文档对象模型)交互。 Looking at what you've written, it looks good so far, but you haven't done anything to actually change the order in which the tags are rendered.看看您所写的内容,到目前为止看起来不错,但是您还没有做任何事情来实际更改标记的呈现顺序。

There are numerous libraries that can do this for you, but I'll recommend doing a little bit of research into JavaScript yourself to learn how to actually manipulate the DOM (considering it's fundamental to what JavaScript does in the browser).有许多库可以为您执行此操作,但我建议您自己对 JavaScript 进行一些研究,以了解如何实际操作 DOM(考虑到它是 JavaScript 在浏览器中执行的操作的基础)。 As a hint, I'll suggest to break the task down into steps that the browser will need to perform:作为提示,我建议将任务分解为浏览器需要执行的步骤:

  1. Isolate the row object (everything between <tr></tr> ) in memory from the DOM.将内存中的行对象( <tr></tr>之间的所有内容)与 DOM 隔离。
  2. Remove the row object from the DOM.从 DOM 中删除行对象。
  3. Re-insert the row object into the DOM at the right place.在正确的位置将行对象重新插入 DOM。

This link from W3Schools provides a good example of how to do exactly that: https://www.w3schools.com/howto/howto_js_sort_table.asp W3Schools 的这个链接提供了一个很好的例子,说明了如何做到这一点: https : //www.w3schools.com/howto/howto_js_sort_table.asp

They also have a number of tutorials and stuff that will help you build more proficiency in both HTML and JavaScript, and also CSS (which is really important for front-end stuff).他们还有许多教程和内容,可以帮助您更熟练地掌握 HTML 和 JavaScript 以及 CSS(这对于前端内容非常重要)。 Best of luck!祝你好运! Let us know if you have any questions!假如你有任何问题请告知我们!

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

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