尝试这样做,如果一个年份值在2个值之间,则会为您分配特定的标题



这里的目标是使它在我将值放入文本框时,它会根据您的年龄分配给您一个标题。然而,它不起作用,JSFiddle给了我以下错误:

"<a class='gotoLine' href='#48:26'>48:26</a> Uncaught SyntaxError:
Unexpected token '&lt;='"

据我所知,这甚至不应该是一个错误。小于或等于的符号是<=,所以我不确定问题出在哪里。

function ShowGeneration() {
var yearBorn;
var generation;
var Boomer
var X
var Millenial
var Z
yearBorn = parseFloat(document.getElementById('yearBox').value);
// insert if statements here to map yearBorn onto generation
if (yearBorn >= 1944 && yearBorn <= 1964)
generation = Boomer;
else {
if (yearBorn >= 1965 && yearBorn <= 1979)
generation = X;
else {
if (yearBorn >= 1980 && yearBorn <= 1994)
generation = Millenial;
else {
if (yearBorn >= 1995 && yearBorn <= 2015)
generation = Z;
}
}
}

document.getElementById('outputDiv').innerHTML = "You belong to the " + generation + " generation.";
}
<p>
What year were you born? <input type="text" id="yearBox" size="6">
</p>
<input type="button" value="Click for Generation" onclick="ShowGeneration();">
<div id="outputDiv"></div>

修复了一些语法和格式,请参阅下文。

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Generations</title>
<script type="text/javascript">
function showGeneration() {
var generation;
var yearBorn = parseFloat(document.getElementById('yearBox').value);
// insert if statements here to map yearBorn onto generation
if (yearBorn >= 1944 && yearBorn <= 1964) {
generation = "Boomer";
}
else if (yearBorn >= 1965 && yearBorn <= 1979) {
generation = "X";
}
else if (yearBorn >= 1980 && yearBorn <= 1994) {
generation = "Millenial";
}
else if (yearBorn >= 1995 && yearBorn <= 2015) {
generation = "Z";
}  
document.getElementById('outputDiv').innerHTML = "You belong to the " + generation + " generation.";
}
</script>
</head>
<body>
<p>
What year were you born? <input type="text" id="yearBox" size="6">
</p>
<input type="button" value="Click for Generation"  onclick="showGeneration();">
<div id="outputDiv"></div>
</body>
</html>

JSFiddle

请注意,任何比1944年轻或比2015年长的人仍然属于undefined一代;您应该在if语句中介绍这两种情况。

我发现错误:

  1. 生成的值必须在引号之间,因为它们是字符串

  2. 失踪年份出生在比较

  3. 缺少用于关闭if和函数的卷曲括号

试试这个

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Generations</title>
<script type="text/javascript">
function ShowGeneration() {
var yearBorn;
var generation;
yearBorn = parseFloat(document.getElementById('yearBox').value);
// insert if statements here to map yearBorn onto generation
if (yearBorn >= 1944 && yearBorn <= 1964)
generation = "Boomer";
else {
if (yearBorn >= 1995 && yearBorn <= 1979)
generation = "X";
else {
if (yearBorn >= 1980 && yearBorn <= 1994)
generation = "Millenial";
else {
if (yearBorn >= 1995 && yearBorn <= 2015)
generation = "Z";
document.getElementById('outputDiv').innerHTML = "You belong to the " + generation + " generation.";
}
}
}
}
</script>
</head>
<body>
<p>
What year were you born? <input type="text" id="yearBox" size="6">
</p>
<input type="button" value="Click for Generation" onclick="ShowGeneration()">
<div id="outputDiv"></div>
</body>
</html>

最新更新