JS 新手,尝试完成一项要求用户输入年龄并使用 Javascript 的作业:
- 检查输入是否为有效整数;
- 如果输入的年龄是迄今为止输入的最低年龄,或迄今为止输入的最高年龄,则会发出一条消息提醒(即“这是我们见过的最低年龄!”/“这是我们的最高年龄”我见过。”)。
我已经获得了#1,但我什至不知道从哪里开始#2。我已将输入的数字记录到控制台,因为我将从那里进行图像比较。我已经开始尝试绘制alertAge() 函数的草图,但不知道该把它放在哪里。
解决这个问题的最佳方法是什么?
document.getElementById("myButton").addEventListener("click", checkAge);
function checkAge() {
var ages = document.getElementById("age").value;
if (isNaN(ages)) {
alert("Value must be a number. Try again!");
}
else {
console.log(ages);
}
}
function alertAge() {
var highest;
var lowest;
if (highest === undefined) { // This is the first age we're seeing
highest = age;
lowest = age;
} else {
if (age > highest)
highest = age; // This is the new highest age
if (age < lowest)
lowest = age; // This is the new lowest age
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label for="age">Enter your age:</label>
<input id="age" />
<button id="myButton" type="submit">Go</button>
</body>
</html>
JS 斌:
最佳答案
对于#1,您可以使用 <input type="number">
而不是在 JS 中检查它是否是数字。
对于#2,您需要将值存储在函数之外。 Read more about Javascript context 。 要在函数外部使用变量,请执行以下操作:
var highest,lowest;
function alertAge() {...};
<小时/>
更精确的解释:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label for="age">Enter your age:</label>
<input type="number" id="age" />
<button onClick="checkAge()">Go</button>
<script>
var highest = null;
var lowest = null;
function alertAge(age) {
if (!highest) {
highest = lowest = age;
} else {
if (age > highest) {
highest = age; // This is the new highest age
alert('new highest', age);
}
if (age < lowest) {
lowest = age; // This is the new lowest age
alert("new lowest", age);
}
}
}
function checkAge() {
var ages = document.getElementById("age").value;
if (ages) alertAge(ages);
}
</script>
</body>
</html>
-
<input type="number">
仅限于数字。 onClick="checkAge()"
每当单击该元素(不必是按钮)时都会调用 checkAge()。highest = lowest = age;
将最低设置为“年龄”,并将最高设置为最低(即“年龄”)。少写一点,你会需要你的能量:)alert('my text')
是典型的 JavaScript 弹出窗口“alert”。-
if (ages)
条件是为了确保我们不会向alertAge()发送奇怪的东西; - 声明
highest
和lowest
函数外部的变量使它们“有点”永久,它允许您即使在函数完成时也可以使用它们。如果您在函数内声明变量,则该变量在函数执行后将不再存在。
关于javascript - 使用 Javascript 来提醒用户输入的最高和最低整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858747/