如何根据HTML元素innerText数值对JS数组进行降序排序?
根据HTML元素innerText对元素数组进行降序排序的实现方法
当然可以根据HTML元素的innerText数值对元素数组进行排序,你的代码存在几个关键问题,修正后就能实现需求:
原代码的问题点
box.children返回的是HTMLCollection(类数组对象),并非标准数组,直接调用sort方法不符合规范,需先转为数组。sort方法的参数是比较函数,原代码的调用方式错误,没有正确定义比较逻辑。- 排序完成后,没有将排序后的元素重新渲染到页面,所以无法看到排序效果。
修正后的完整代码
JavaScript 代码
const addBtn = document.getElementById('add-btn'); const addIpt = document.getElementById('add-ipt'); const box = document.getElementById('box'); const sortBtn = document.getElementById('sort-btn'); let numInc = 0; addBtn.addEventListener('click', () => { const boxNum = addIpt.value; box.innerHTML += `<div class="inbox" id="inbox${numInc}">${boxNum}</div>`; empty(); numInc++; }); function empty() { addIpt.value = ''; } function parseAndOrder() { // 将HTMLCollection转为标准数组 const numArr = Array.from(box.children); // 根据innerText的数值降序排序 numArr.sort((el1, el2) => { const num1 = parseInt(el1.innerText, 10); const num2 = parseInt(el2.innerText, 10); return num2 - num1; }); // 清空容器后重新插入排序后的元素 box.innerHTML = ''; numArr.forEach(el => box.appendChild(el)); } sortBtn.addEventListener('click', parseAndOrder);
HTML 代码
<!DOCTYPE html> <html> <head> <title>Stackoverflow Questions</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="stackoverflow.css"> </head> <body> <input id="add-ipt" type="number"> <button id="add-btn">Add</button> <button id="sort-btn">Sort</button> <div id="box"></div> </body> <script src="stackoverflow.js"></script> </html>
关键修改说明
- 转为标准数组:用
Array.from(box.children)把类数组的HTMLCollection转为真正的数组,确保sort方法正常工作。 - 正确的排序比较函数:
sort方法传入的函数接收两个元素参数,分别解析它们的innerText为整数,通过num2 - num1实现降序排序。 - 重新渲染元素:排序后先清空
box容器,再将排序后的元素依次追加进去,这样页面就能显示排序后的结果。
内容的提问来源于stack exchange,提问作者SamBoone
相关产品推荐
相关产品推荐

