ParseFloat html

时间:2014-02-28 00:16:03

标签: html parsefloat

我是一名刚学HTML的大学生。我必须完成的任务是一个简单的成绩计算器。只有一个按钮可以计算所有内容,值会转到三个空文本字段(总计,平均值和百分比)。我遇到的问题是总计算并显示在字段中,但数字后跟[object]。平均字段显示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;">

1 个答案:

答案 0 :(得分:0)

由于您首先将History作为变量名称,但在计算/分配history的值时使用了total,这是一个不同的变量 - JavaScript 中的标识符区分大小写。

在这一点上,你没有让你的脚本中止有关于未定义变量的错误的唯一原因是window.history存在 - 它是保持窗口当前导航历史的对象。 (所有全局变量都是窗口对象的属性,因此您对history的使用将被解析为。)由于它是一个对象,[object]是将结果转换为字符串时得到的结果上下文(通过使用+发生,它是加法和字符串连接运算符。)

除此之外,将所有代码写入onclick处理程序是一种糟糕的风格。去学习如何使用适当的函数来做下面的事情; - )