制作一个简单的JavaScript程序,根据年龄和婚姻状况对某些保险括号下的用户进行分类。以下程序有效,但是当我测试程序时,我无法让程序正确区分3级和4级保险。我是javascript的新手所以请原谅如果我有些傻话。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title> Insurance Program </title>
<script type = "text/javascript">
function insurance(form)
{
var fname = form.firstname.value;
var sname = form.surname.value;
var age = form.age.value;
var insurance;
var marital = form.maritalstatus.value;
document.write(marital);
if (marital = 2 && age >= 30)
{
insurance = "Grade 1";
}
else if (marital = 1 && age > 30)
{
insurance = "Grade 2";
}
else if (marital = 2 && age < 30)
{
insurance = "Grade 3";
}
else if (marital = 1 && age < 30)
{
insurance = "Grade 4";
}
document.write("Thank you " + fname + " " + sname + "<br>");
document.write("You belong to " + insurance + " Insurance");
}
</script>
</head>
<body>
<h4> Insurance Program </h4>
<form>
Enter your first-name : <input type = "text" name="firstname">
Enter your surname : <input type = "text" name="surname"> <br>
Enter your age: <input type = "text" name="age"> <br>
Select your current marital status
<Select id ="maritalstatus" name = "maritalstatus">
<option value = "1"> Single </option>
<option value = "2"> Married </option>
</Select>
<input type = "submit" value = "submit" onclick="insurance(this.form)">
</form>
</body>
</html>
答案 0 :(得分:3)
首先,当您使用=
时,您正在使用===
。示例:
if (martial === 2 && age >= 30)
martial = 2
和martial = 1
总是如此,所以最后两个ifs是相同的。
参考:=
是assignment operator,==
和===
是comparison operators。
if (parseInt(marital, 10) === 2 && parseInt(age, 10) >= 30) {
ins = "Grade 1";
}
else if (parseInt(marital, 10) === 1 && parseInt(age, 10) >= 30) {
ins = "Grade 2";
}
else if (parseInt(marital, 10) === 2 && parseInt(age, 10) < 30) {
ins = "Grade 3";
}
else if (parseInt(marital, 10) === 1 && parseInt(age, 10) < 30) {
ins = "Grade 4";
}
答案 1 :(得分:2)
你的问题是每一行看起来像这样:
martial = 1 && ...
marital = 1
将marital
设置为1
。你想比较 marital
到1
,所以请使用双等号:
martial == 1 && ...
答案 2 :(得分:0)
您在=
个操作数中误用了if
符号,如果您需要比较值,请使用==
或===
(用于严格类型检查)
答案 3 :(得分:0)
你的条件应该是'=='
martial = 2&amp;&amp;年龄> = 30
martial == 2&amp;&amp;年龄> = 30
因为=是赋值运算符,==是比较。