gpt4 book ai didi

javascript - 我无法解析 getElementsByClass 函数

转载 作者:行者123 更新时间:2023-11-28 18:09:43 24 4
gpt4 key购买 nike

我正在尝试做一个成绩计算器网站,但我似乎无法将输入从字符串转换为整数。这是我的代码:

 <form  name="myform" action="" method="GET">
<div>
<label for="cmps200">CMPS 200</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<label for="cmps211">CMPS 211</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<label for="cmps212">CMPS 212</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<input id="btn" type="button" name="btn" value="Submit" onclick="myF()">
<p> </p>

</div>
</form>
<小时/>
function myF() {
var courses3 = document.getElementsByClassName("threeCredits");
var sum = 0;

for(var i = 0; i < courses3.length; i++) {
sum += parseInt(courses3[i]);
}

if(sum===0 || sum<=0){
alert("Please enter valid inputs!");
} else {
alert(sum/9);
}
}

每次我按下提交按钮时,我都会得到 NaN。请帮忙!

最佳答案

您的courses3[i]是一个元素,而不是它的值。使用courses3[i].value .

也在你的 if 中条件<=实际上还检查第一个,即 === 。所以你可以删除它

function myF() {
var courses3 = document.getElementsByClassName("threeCredits");
var sum = 0;

for(var i = 0; i < courses3.length; i++) {
sum += parseInt(courses3[i].value);
}

if( sum <= 0 ){
alert("Please enter valid inputs!");
} else {
alert(sum/9);
}
}
<form  name="myform" action="" method="GET">
<div>
<label for="cmps200">CMPS 200</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<label for="cmps211">CMPS 211</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<label for="cmps212">CMPS 212</label>
<input type="number" name="three" class="threeCredits">
<br>
</div>

<div>
<input id="btn" type="button" name="btn" value="Submit" onclick="myF()">
<p> </p>

</div>
</form>

关于javascript - 我无法解析 getElementsByClass 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869582/

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