DOM / Javascript没有返回值,结果产生NAN。找不到错误?

时间:2015-05-03 00:13:16

标签: javascript dom

我有一个逻辑错误,似乎无法找到它。我认为我正确地通过ID“获取”元素,但它会产生NAN。对此有任何帮助表示赞赏 我不确定我做错了什么,欢迎任何建议。我是DOM新手,对Javascript不是很熟悉。

var avgGrade
function calcAvg()
   {
    avgGrade = document.getElementById("finalExam") +    
document.getElementById("homework") + document.getElementById("projects");
        alert("Your average is " + avgGrade);
    document.getElementById("stuAverage").value = avgGrade;
   }

//-->
</script>
</head>
<body>
<h1>Calculate average</h1>
<h3>Enter the following information and then press the <b>AVERAGE</b> button 

to calculate 
your grade.</h3>
<p>To clear the data fields, click here <b><a 

href="javascript:location.reload(true)">Refresh this page</a></b></p>
<form action="#" name="gradeInfo" id="gradeInfo">
<p>
Enter Final Exam Grade:
<input type="text" name="finalExam" id="finalExam" size="4" /><br />
Enter Homework Grade:
<input type="text" name="homework" id="homework" size="4" /><br />
Enter Projects Grade:
<input type="text" name="projects" id="projects" size="4" /><br />
<br /><br />
<input type="button" value="AVERAGE" onclick="calcAvg()" />

<br /><br />
Your Average is:
<input type="text" name="stuAverage" id="stuAverage" size="4" /><br />
</p>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

首先在;

结尾处遗漏了var avgGrade

其次,您需要获取输入值而不是输入本身。

document.getElementById("homework").value

第三,您需要使用parseInt

将值从字符串转换为整数
avgGrade = parseInt(document.getElementById("finalExam").value) +
    parseInt(document.getElementById("homework").value) +
    parseInt(document.getElementById("projects").value);

jsfiddle DEMO

P.S。你必须把它除以等级数来得到平均值。

答案 1 :(得分:0)

获取您需要编写的输入字段中的值 -

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {  
    public static void main(String[] args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(Application.class).headless(false).run(args);
    AppPrincipalFrame appFrame = context.getBean(AppPrincipalFrame.class);
}