我如何使用javascript按列升序排列

问题描述 投票:0回答:1

我想要的是,当我单击标题时,它将按列的升序排序,我该怎么做?请帮助我,谢谢

function createTable() {
  var row = document.getElementById('rows').value;
  var col = document.getElementById('cols').value;
  var table = document.getElementById('tab');
  const max = 1000;
  const min = 1;
  console.log(row + " " + col);
  for (let i = 0; i < row; i++) {
    const tr = document.createElement('tr');
    const th = document.createElement('th');
    for (let j = 0; j < col; j++) {
      const td = document.createElement('td');
      td.innerHTML = Math.round(Math.random() * (max - min));
      tr.appendChild(td);
    }
    table.appendChild(tr); // append to table
  }
}
document.getElementById('but').addEventListener("click", createTable);
<label for="row">Enter row</label>
<input type="text" name="row" id="rows">
<label for="col">Enter column</label>
<input type="text" name="col" id="cols">
<table id="tab"></table>
<button type="button" id="but">Enter</button>
javascript html
1个回答
0
投票
  1. 在行中创建innerText个标签的td的数组
  2. 使用Array.sort()排序数组
  3. 遍历数组的每个数字并在td的每个row上设置文本

例如:

function mySort(){
        var table = document.querySelector("table");
        var arr = [];
        [...table.querySelectorAll("tr td")].forEach((td)=>{
         arr.push(parseInt(td.textContent));
       });
    arr.sort();
    arr.forEach((val,i)=>{
     [...table.querySelectorAll("tr td")][i].textContent = val;
   });
  }
function createTable() {
  var row = document.getElementById('rows').value;
  var col = document.getElementById('cols').value;
  var table = document.getElementById('tab');
  const max = 1000;
  const min = 1;
  console.log(row + " " + col);
  for (let i = 0; i < row; i++) {
    const tr = document.createElement('tr');
    const th = document.createElement('th');
    for (let j = 0; j < col; j++) {
      const td = document.createElement('td');
      td.innerHTML = Math.round(Math.random() * (max - min));
      tr.appendChild(td);
    }
    table.appendChild(tr); // append to table
}
}
document.getElementById('but').addEventListener("click", createTable);
<label for="row">Enter row</label>
<input type="text" name="row" id="rows">
<label for="col">Enter column</label>
<input type="text" name="col" id="cols">
<table id="tab"></table>
<button type="button" id="but">Enter</button>
<button onclick="mySort()">Sort</button>
© www.soinside.com 2019 - 2024. All rights reserved.