【问题标题】:How to sort a list from user input from lowest value to highest value in HTML如何在HTML中从用户输入的最低值到最高值对列表进行排序
【发布时间】:2019-03-22 01:44:34
【问题描述】:

我正在尝试编写一个代码,该代码将给出列表中数字的总和、平均值、最小值、最大值和频率,并将列表从最小值到最大值排序。在其他人的帮助下,我能够得到总和、平均值、最大值、最小值和频率,但不知道如何将列表从最大值排序到最小值。我想要的代码是在代码末尾有一个按钮

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>
<head>
  
  <link rel="stylesheet" type="text/css" href="style.css">
  
  </head>
  
  
<body>

    <link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->

<input type='number' id='input'>

<!--- This is the button that adds the number to the list --->

<input type='button' value='add to list' id='add' disabled="disabled">

<!--- Here we have a title for the list --->

<div class="title">Topics</div>

<!--- This will list all of the numbers --->

<ul id='list'></ul>

<!--- When clicked, this buttons alert the user with the numbers --->

<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<button id="frequency"> Frequency </button>


<div>

  <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

</div>
  
  <script>
    
    let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);

// This will add the input number to the list and clear the input

function addClick() {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  update(input.value);
  input.value = "";
  add.disabled = "disabled";
 
}

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable() {
  if (this.value === "") {
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.textContent;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');
  
  alert(text);
}

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}

function avgClick() {
  alert("The average of your numbers is: " + avg);
}

function minClick() {
  alert("The smaller number is: " + min);
}

function maxClick() {
  alert("The greater number is: " + max);
}

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
    
    
  </script>   


</body>
  

  
  
</html>

用户可以按从最低值到最高值对列表进行排序。

【问题讨论】:

  • 你可以有一个数组来存储所有的数字。并使用 array.sort() 对其进行良好排序,然后将其重新渲染到 html dom。

标签: javascript html list user-input


【解决方案1】:

适用于您的情况的简单示例,https://www.w3schools.com/howto/howto_js_sort_list.asp

您只需将其从按字母顺序排列更改为按数字排列即可。开始吧,对列表从低到高从高到低进行排序,然后重新排列 DOM 上的元素。

低-高

function lowHigh() {
    var list, i, switching, b, shouldSwitch;
    list = document.getElementById("list");
    switching = true;
    /* Make a loop that will continue until
    no switching has been done: */
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        b = list.getElementsByTagName("li");
        // Loop through all list items:
        for (i = 0; i < (b.length - 1); i++) {
            // Start by saying there should be no switching:
            shouldSwitch = false;
            /* Check if the next item should
            switch place with the current item: */
            if (b[i].innerText > b[i + 1].innerText) {
                shouldSwitch = true;
                break;
            }
        }
        if (shouldSwitch) {
            /* If a switch has been marked, make the switch
            and mark the switch as done: */
            b[i].parentNode.insertBefore(b[i + 1], b[i]);
            switching = true;
        }
    }

高低

// Change to
if (b[i].innerText < b[i + 1].innerText) 

let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);

// This will add the input number to the list and clear the input

function addClick() {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  update(input.value);
  input.value = "";
  add.disabled = "disabled";

}

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable() {
  if (this.value === "") {
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.textContent;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');

  alert(text);
}

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}

function avgClick() {
  alert("The average of your numbers is: " + avg);
}

function minClick() {
  alert("The smaller number is: " + min);
}

function maxClick() {
  alert("The greater number is: " + max);
}

function lowHigh() {
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("list");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    b = list.getElementsByTagName("li");
 
    // Loop through all list items:
    for (i = 0; i < (b.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Check if the next item should
      switch place with the current item: */
      if (b[i].innerText > b[i + 1].innerText) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }


}

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
<!DOCTYPE html>

<html>

<head>

  <link rel="stylesheet" type="text/css" href="style.css">

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- This only allows the user to input numbers --->

  <input type='number' id='input'>

  <!--- This is the button that adds the number to the list --->

  <input type='button' value='add to list' id='add' disabled="disabled">

  <!--- Here we have a title for the list --->

  <div class="title">Topics</div>

  <!--- This will list all of the numbers --->

  <ul id='list'></ul>

  <!--- When clicked, this buttons alert the user with the numbers --->

  <button id="sum"> Sum </button>
  <button id="max"> Max </button>
  <button id="min"> Min </button>
  <button id="avg"> Avg </button>
  <button id="frequency"> Frequency </button>

  <p><button onclick="lowHigh()">Sort</button></p>


  <div>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

  </div>



</body>



</html>

【讨论】:

    【解决方案2】:

    因为您使用数字作为列表项值,我们可以像这样使用数字数组对其进行排序。

    var list = document.getElementById('list');
    function sort(dir){
    	var li = list.getElementsByTagName("li");
    	// populate data into array
    	var data=[];
    	for(var a in li) {
    		if (typeof li[a].innerText !='undefined') data.push(parseInt(li[a].innerText,10));
    	}
    	// create sort number function as sort parameter, we need this because default sort function will sort it alphabetically
    	var sortNum = function (a,b) {
            return a - b;
        }
    	// start sorting
    	if (dir == 'asc') data.sort(sortNum);
    	else data.sort(sortNum).reverse();
    	// clear list
    	while (list.lastChild) {
    		list.removeChild(list.lastChild);
    	}
    	// generate new list items
    	for (var x=0; x<data.length; x++) {
    		var new_li = document.createElement("li");
    		new_li.textContent = data[x];
    		list.appendChild(new_li);
    	}
    }
    <input type="button" value="asc" onclick="sort('asc')"><input type="button" value="desc" onclick="sort('desc')"> 
    <ul id="list">
      <li>2</li>
      <li>3</li>
      <li>16</li>
      <li>21</li>
      <li>15</li>
    </ul>

    【讨论】:

      【解决方案3】:

      我提供了 2 个解决方案;一个不会在每次更新时存储和计算值的更新版本(版本 1)和另一个版本,它是您自己的扩展(版本 2):

      版本 1:

      let list = document.getElementById("list");
      let input = document.getElementById("input");
      let add = document.getElementById("add");
      
      let items = [];
      addItem = () => {
        var li = document.createElement("li");
        li.textContent = input.value;
        list.appendChild(li);
        items.push(+input.value);
        input.value = "";
        add.disabled = "disabled";
      }
      
      // This allows the "add to list" button to be turned on/off depending if the user has typed in a number
      function enableDisable() {
        if (this.value === "") {
          add.disabled = "disabled";
        } else {
          add.removeAttribute("disabled");
        }
      }
      
      // This functions will alert the numbers
      // You can pull these out into functions if you would like. 
      getSum = () => alert(`The sum of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)}`);
      getAvg = () => alert(`The average of your numbers is: ${items.reduce((acc, v)=>acc+=v,0)/items.length}`);
      getMin = () => alert(`The smaller number is: ${Math.min(...items)}`);
      getMax = () => alert(`The greater number is: ${Math.max(...items)}`);
      getAscending = () => alert(JSON.stringify(items.sort(), null, 4));
      getDescending = () => alert(JSON.stringify(items.sort((a, b) => b - a), null, 4));
      getFrequency = () => alert(
        Object.entries(items.reduce((acc, v) => {
          if (acc[v]) {
            acc[v]++;
          } else {
            acc[v] = 1;
          }
          return acc;
        }, {})).map(([number, fqy]) =>
          `The number ${number} appeared ${fqy} time(s) in the list`
        ).join("\n"));
      .title {
        font-weight: bold;
        margin-top: 1em;
      }
      <!DOCTYPE html>
      
      <html>
      
      <head>
      
        <link rel="stylesheet" type="text/css" href="style.css">
      
      </head>
      
      
      <body>
      
        <link rel="stylesheet" type="text/css" href="style.css">
        <!--- This only allows the user to input numbers --->
      
        <input type='number' id='input' oninput="enableDisable()">
      
        <!--- This is the button that adds the number to the list --->
      
        <input type='button' value='add to list' id='add' onClick="addItem()" disabled="disabled">
      
        <!--- Here we have a title for the list --->
      
        <div class="title">Topics</div>
      
        <!--- This will list all of the numbers --->
      
        <ul id='list'></ul>
      
        <!--- When clicked, this buttons alert the user with the numbers --->
      
        <button onClick="getSum()"> Sum </button>
        <button onClick="getMax()"> Max </button>
        <button onClick="getMin()"> Min </button>
        <button onClick="getAvg()"> Avg </button>
        <button onClick="getFrequency()"> Frequency </button>
        <button onClick="getAscending()"> Sort Ascending </button>
        <button onClick="getDescending()"> Sort Descending </button>
      
        <div>
          <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
        </div>
      </body>
      
      </html>

      版本 2:

      var list = document.getElementById("list");
      var input = document.getElementById("input");
      var add = document.getElementById("add");
      var avg = 0;
      var sum = 0;
      var min = -Infinity;
      var max = Infinity;
      var frequency = Object.create(null);
      var ascending = [];
      var descending = [];
      
      // This will add the input number to the list and clear the input
      
      function addClick() {
        var li = document.createElement("li");
        li.textContent = input.value;
        list.appendChild(li);
        update(input.value);
        input.value = "";
        add.disabled = "disabled";
      
      }
      
      // This allows the "add to list" button to be turned on/off depending if the user has typed in a number
      
      function enableDisable() {
        if (this.value === "") {
          add.disabled = "disabled";
        } else {
          add.removeAttribute("disabled");
        }
      }
      
      // This will calculate and update all variable values
      
      function update(enteredValue) {
        frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
        sum = 0;
        min = Infinity;
        max = -Infinity;
        var count = 0;
        for (var i of list.children) {
          let val = +i.textContent;
          sum += val;
          if (val > max) max = val;
          if (val < min) min = val;
          count++;
        }
        avg = sum / count;
        ascending = Object.keys(frequency).sort();
        descending = Object.keys(frequency).sort((a, b) => b - a);
      }
      
      function frequencyClick() {
        let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
          return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
        }, []).join('\n');
      
        alert(text);
      }
      
      // This functions will alert the numbers
      
      function sumClick() {
        alert("The sum of your numbers is: " + sum);
      }
      
      function avgClick() {
        alert("The average of your numbers is: " + avg);
      }
      
      function minClick() {
        alert("The smaller number is: " + min);
      }
      
      function maxClick() {
        alert("The greater number is: " + max);
      }
      
      function ascending() {}
      
      function descending() {}
      
      // Here we add all events
      input.addEventListener("input", enableDisable);
      add.addEventListener("click", addClick);
      document.getElementById("avg").addEventListener("click", avgClick);
      document.getElementById("sum").addEventListener("click", sumClick);
      document.getElementById("min").addEventListener("click", minClick);
      document.getElementById("max").addEventListener("click", maxClick);
      document.getElementById("frequency").addEventListener("click", frequencyClick);
      document.getElementById("ascending").addEventListener("click", () => alert(JSON.stringify(ascending, null, 4)));
      document.getElementById("descending").addEventListener("click", () => alert(JSON.stringify(descending, null, 4)));
      .title {
        font-weight: bold;
        margin-top: 1em;
      }
      <!DOCTYPE html>
      
      <html>
      
      <head>
      
        <link rel="stylesheet" type="text/css" href="style.css">
      
      </head>
      
      
      <body>
      
        <link rel="stylesheet" type="text/css" href="style.css">
        <!--- This only allows the user to input numbers --->
      
        <input type='number' id='input'>
      
        <!--- This is the button that adds the number to the list --->
      
        <input type='button' value='add to list' id='add' disabled="disabled">
      
        <!--- Here we have a title for the list --->
      
        <div class="title">Topics</div>
      
        <!--- This will list all of the numbers --->
      
        <ul id='list'></ul>
      
        <!--- When clicked, this buttons alert the user with the numbers --->
      
        <button id="sum"> Sum </button>
        <button id="max"> Max </button>
        <button id="min"> Min </button>
        <button id="avg"> Avg </button>
        <button id="frequency"> Frequency </button>
        <button id="ascending"> Sort Ascending </button>
        <button id="descending"> Sort Descending </button>
      
        <div>
          <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
        </div>
      </body>
      
      </html>

      希望对你有帮助,

      【讨论】:

      • 错误。该死,我已经让它实际上重新排列了元素,这就是我认为他想要的。
      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 2019-10-10
      • 2011-08-21
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2020-11-18
      • 2018-12-21
      相关资源
      最近更新 更多