gpt4 book ai didi

javascript - 在 onchange 和通过文本框将数字存储在数组中时遇到问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:54 34 4
gpt4 key购买 nike

我的 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 - 在 onchange 和通过文本框将数字存储在数组中时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032301/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com