javascript – 在onchange上遇到麻烦并通过文本框将数字存储在数组中

我无法使用onchange工作,并通过文本框将数字存储在数组中.
我想要的代码是获取输入到文本框中的数字的统计信息.我这样做是让用户在文本框中输入数字,然后按Enter键显示这些数字.在将数字放入列表以显示输入的数字之前,应将数字放入数组中.但是,当按下Enter键或单击文本框时,我不会触发onchange时出现此错误.

Here is an image of the error I am getting when inspecting the code

随着数字中存储的数字,我想尝试获得数字的均值.但是,我不断收到错误“NaN”,这让我觉得我的数字没有正确存储到数组中.

这是代码:

<html>
<head>
  <title>Stats</title>
</head>

<p>Array is called numbers. numbers.sort();</p>

<div id="stats">

  <input type ="text" id="value" onchange="list()"> <!-- Getting the Onchange Error here -->

  <button id="button1" onclick = "list()">Enter</button>

  <ul id="list1">
  </ul>

<button id="stat_button" onclick="calculateMean()">Get Statistics</button>

<p id="mean">Mean= </p>

</div>



<script>

function list() {

      var liElement = document.createElement("li"); //Creating new list element//

      var ulElement = document.getElementById("list1");   //Get the ulElement//

      var input = document.getElementById("value").value; //Get the text from the text box//

      var numbers = []; //create Array called numbers
      numbers.push(input);//adds new items to the array

      //for loop//
      for(var i=0; i < numbers.length; i++) {
        liElement.innerHTML = numbers[0];  //Puts the array into the list for display//
        ulElement.appendChild(liElement); //add new li element to ul element//
      }
  }


function calculateMean() {

      var meanTotal = 0;
      var meanAverage = 0;
      var meanArray = [];

      for (var i = 0; i < meanArray.length; i++) {
        meanTotal += meanArray[i];
      }
      meanAverage = (meanTotal / meanArray.length);

      document.getElementById("mean").innerHTML = meanAverage;

}

</script>

解决方法:

尝试通过addEventListener添加它,而不是像这样内联:

document.getElementById('value').addEventListener('change', function(e){
    list()
})
上一篇:javascript-dropdown onchange事件直到第二个实例才触发


下一篇:(集合输出)LinkedHashMap子类