在网站上显示数据时,重要的是提供使用户更轻松地浏览数据的功能。其中一项功能就是能够对数据进行排序。
对数据进行排序是指将数据按照指定的值,按升序或降序排列。我们可以使用 JavaScript 在网站的客户端手动处理数据排序。如果您正在开发静态网站或消除服务器中数据排序的负担,这尤其有用。
在本教程中,我们将使用 JavaScript 将模拟 JSON 响应中的数据显示到 HTML 表中。我们还将包含使表格可根据表标题中的值进行排序的功能。
这是成品。单击任意表格标题即可对表格进行相应排序。
compareFunction(a, b) 返回值 | 排序顺序 |
---|---|
> 0 | 排序 a 之后 b |
将 a 排序在 b 之前 | |
=== 0 | 保持 a 和 b 的原始顺序 |
来源:MDN
关于排序方法需要注意的另一件事是它会改变它所操作的原始数组。这意味着它改变了我们原始数组的值。
我们可以通过使用扩展语法来避免改变原始数组[...]
现在我们可以创建排序函数了。这就是我们的排序函数的逻辑:
<div class="table-container"> <table class="data-table"> </table> </div>
我们的排序函数需要三个参数:
我们通过将innerHTML 设置为空白字符串来清除tableContent 元素中的内容。然后,我们使用 .sort() 方法和 direction 参数来确定数据应如何排序。我们反转比较函数以便按降序排序。通过这种方式使用比较函数,我们可以对数据进行排序,而不管值的类型(字符串、整数、浮点数等)
最后,我们将 sortedData 作为表内容中的新值传递。
现在,我们将排序函数传递到表格按钮的单击事件侦听器中,并处理切换排序方向。
<div class="table-container"> <table class="data-table"> <thead> <tr> <th><button id="name">Name</button></th> <th><button id="type">Type</button></th> <th><button id="hp">HP</button></th> <th><button id="attack">Attack</button></th> <th><button id="defense">Defense</button></th> <th><button id="spAttack">Sp. Attack</button></th> <th><button id="spDefense">Sp. Defense</button></th> <th><button id="speed">Speed</button></th> <th><button id="total">Total</button></th> </tr> </thead> <tbody id="table-content"></tbody> </table> </div>
在此函数中,我们通过在按钮上设置 data-dir 属性来处理切换以确定排序方向。我们还将更新 CSS 以根据排序方向在按钮旁边显示一个图标:
.table-container { width: 100%; overflow: scroll; } table { width: 100%; }
我们不想让图标显示在所有以前单击的按钮上,因此我们将定义一个 resetButtons 函数,该函数删除任何未单击的按钮上的 data-dir 属性。
.table-container { margin: auto; max-width: 1200px; min-height: 100vh; overflow: scroll; width: 100%; } table { border-collapse: collapse; width: 100%; } thead tr { border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; height: 1px; } th { font-weight: bold; height: inherit; padding: 0; } th:not(:first-of-type) { border-left: 1px solid #ddd; } th button { background-color: #eee; border: none; cursor: pointer; display: block; font: inherit; height: 100%; margin: 0; min-width: max-content; padding: 0.5rem 1rem; position: relative; text-align: left; width: 100%; } tbody tr { border-bottom: 1px solid #ddd; } td { padding: 0.5rem 1rem; text-align: left; }
我们会将该函数传递到按钮事件侦听器中,以便在单击新按钮时重置以前的按钮
const response = { "pokedata": [ { "name": "Bulbasaur", "type": "Grass", "hp": 45, "attack": 49, "defense": 49, "spAttack": 65, "spDefense": 65, "speed": 45, "total": 318 }, ... ] }
这样,我们就完成了!我们仅使用普通 JavaScript 创建了一个可排序的表格!
const tableContent = document.getElementById("table-content")
const createRow = (obj) => { const row = document.createElement("tr"); const objKeys = Object.keys(obj); objKeys.map((key) => { const cell = document.createElement("td"); cell.setAttribute("data-attr", key); cell.innerHTML = obj[key]; row.appendChild(cell); }); return row; };
const getTableContent = (data) => { data.map((obj) => { const row = createRow(obj); tableContent.appendChild(row); }); };
window.addEventListener("load", () => { getTableContent(response.pokedata); });
const tableButtons = document.querySelectorAll("th button");
const sortData = (data, param, direction = "asc") => { tableContent.innerHTML = ''; const sortedData = direction == "asc" ? [...data].sort(function (a, b) { if (a[param] < b[param]) { return -1; } if (a[param] > b[param]) { return 1; } return 0; }) : [...data].sort(function (a, b) { if (b[param] < a[param]) { return -1; } if (b[param] > a[param]) { return 1; } return 0; }); getTableContent(sortedData); };
window.addEventListener("load", () => { getTableContent(response.pokedata); [...tableButtons].map((button) => { button.addEventListener("click", (e) => { if (e.target.getAttribute("data-dir") == "desc") { sortData(response.pokedata, e.target.id, "desc"); e.target.setAttribute("data-dir", "asc"); } else { sortData(response.pokedata, e.target.id, "asc"); e.target.setAttribute("data-dir", "desc"); } }); }); });
th button::after { position: absolute; right: 0.5rem; } th button[data-dir="asc"]::after { content: url("data:image/svg+xml,%3Csvg xmlns='https://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpolygon points='0, 0 8,0 4,8 8' fill='%23818688'/%3E%3C/svg%3E"); } th button[data-dir="desc"]::after { content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpolygon points='4 0,8 8,0 8' fill='%23818688'/%3E%3C/svg%3E"); }
const resetButtons = (event) => { [...tableButtons].map((button) => { if (button !== event.target) { button.removeAttribute("data-dir"); } }); };
window.addEventListener("load", () => { getTableContent(response.pokedata); [...tableButtons].map((button) => { button.addEventListener("click", (e) => { resetButtons(e); if (e.target.getAttribute("data-dir") == "desc") { sortData(response.pokedata, e.target.id, "desc"); e.target.setAttribute("data-dir", "asc"); } else { sortData(response.pokedata, e.target.id, "asc"); e.target.setAttribute("data-dir", "desc"); } }); }); });
以上就是创建具有排序功能的启用 JavaScript 的 HTML 表的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号