使用if..else语句根据年龄计算点数,脚本仅显示第一个值

时间:2011-12-22 04:18:13

标签: javascript html forms if-statement

我希望有JavaScript经验的人能够通过这个脚本来告诉我我做错了什么,可以在jsfiddle看到这个脚本的应用。 第一个脚本showAge()应该从出生日期获得年龄,然后用结果填充txt字段“age”。第二个脚本然后应该解析“age”字段并检查结果是否与任何条件匹配(在if..else语句中显示),然后使用基于if的点填充两个字段(rsltf和rsltq)。 .else声明。但是现在它只输出10和16(两个if..else if语句的第一个值),无论年龄如何。我真的无法弄清楚:/

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quebec and Federal Immigration Points Calculator</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript"> 
function showAge(){ 
var d =document.getElementById('dob').value.split('/'); 
var today = new Date(); 
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();  
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))  
{
     t = age--;  
}
else {
t = age
}
form.age.value = t; 
} 
</script> 
<script type="text/javascript">
function compute(form)
{
var a = parseInt(form.age.value, 10) || 0; 
if (21 <= a <= 49){
    f = 10;
}
else if (20 == a == 50){
    f = 8;
}
else if (19 == a == 51){
    f = 6;
}
else if (18 == a == 52){
    f = 4;
}
else if (17 == a == 53){
    f = 2;
}
else if (17 > a > 53){
    f = 0;
}
form.rsltf.value = f;
if (18 <= a <= 35){
    q = 16;
}
else if (a == 36){
    q = 14;
}
else if (a == 37){
    q = 12;
}
else if (a == 38){
    q = 10;
}
else if (a == 39){
    q = 8;
}
else if (a == 40){
    q = 6;
}
else if (a == 41){
    q = 4;
}
else if (a == 42){
    q = 2;
}
else if (18 > a > 43){
    q = 0;
}
form.rsltq.value = q;   
}
</script>
</head>
<body>
<form name="form">
<p>Your Date of Birth (format:<strong>dd/mm/yyyy</strong>)</p><br />
<input onBlur="compute(this.form)" onchange="showAge()" name="dob" id="dob" />
<p>Your Age</p><input name="age" type="text" style="font-size: 15px" value="" size="7" readonly>
<h1>Your education</h1>

<INPUT NAME="calc" VALUE="Calculate" TYPE="button" onClick="compute(this.form)"><br />
<input name="rsltf" type="text" style="font-size: 50px" value="" size="20" readonly /><br />
<input name="rsltq" type="text" style="font-size: 50px" value="" size="20" readonly />
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

您无法在javascript中执行此操作:21 <= a <= 49

你必须21 <= a && a <= 49

21 <= a <= 49被解释为(21 <= a) <= 49,因此它将bool与49进行比较。当转换为数字时,bool变为1或0,因此它将始终小于49。

答案 1 :(得分:1)

此代码根本不起作用:

function compute(form)
{
var a = parseInt(form.age.value, 10) || 0; 
if (21 <= a <= 49){
    f = 10;
}
else if (20 == a == 50){
    f = 8;
}
else if (19 == a == 51){
    f = 6;
}
else if (18 == a == 52){
    f = 4;
}
else if (17 == a == 53){
    f = 2;
}
else if (17 > a > 53){
    f = 0;
}

JavaScript会像这样解释:

21 <= a <= 49
(21 <= a) <= 49
(1 or 0) <= 49
true

你需要详细说明:

(21 <= a) && (a <= 49)

这段代码怎么样:

17 == a == 53

该怎么办?