我是一个正在学习HTML的大学生。我必须完成的任务是一个简单的等级计算器。只有一个按钮可以计算所有内容,并且值会转到三个空文本字段(总计、平均值和百分比)。我遇到的问题是总数是计算出来的,并显示在字段中,但是数字后面跟着对象。平均字段显示NaN,百分比字段保持为空。这是我的密码。
<input type="button" value="Click to calculate"
onclick="fullmark = parseFloat(document.getElementById('fullBox').value);
science = parseFloat(document.getElementById ('scienceBox').value);
math = parseFloat(document.getElementById('mathBox').value);
computer = parseFloat(document.getElementById('computerBox').value);
english = parseFloat(document.getElementById('englishBox').value);
History = parseFloat(document.getElementById('historyBox').value);
total=science+math+computer+english+history;
average=(total/5);
percentage=(total/fullmark)*100;
document.getElementById('totalBox').value=total;
document.getElementById('averageBox').value=average;
document.getElementById('percentageBox').value=percentage;">发布于 2014-02-28 00:21:40
由于您首先将History作为变量名编写,但是在计算/分配total值时使用了history,也就是说,JavaScript中的不同变量标识符区分大小写。
在那个时候,您没有因为一个未定义变量的错误而中止脚本的唯一原因是window.history存在--它是保存窗口当前导航历史的对象。(所有全局变量都是window对象的属性,因此您对history的使用将被解析为。)因为它是一个对象,所以[object]是将它传输到字符串上下文时得到的结果(这是通过使用+来实现的,它既是加法运算符,也是字符串连接运算符)。
除此之外,将所有这些代码编写到onclick处理程序中是一种很糟糕的风格。学习如何在下面这样的事情中使用适当的函数;-)
https://stackoverflow.com/questions/22083615
复制相似问题