我被要求创建一个网页,用户可以插入年龄并获取一些消息。如果用户未满 21 岁,请发送至 disney.com。不知道怎么寄。到目前为止,这就是我所做的。我不确定该功能是否正确,如果我插入年龄并单击,HTML 按钮和文本字段将无法正常工作。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>check is over 21 or not</title>
<script>
function CalAge(birthDateString) {
var today = new Date();
var birthDate = new Date(birthDateString);
var age = today.getFullYear() - birthDate.getFullYear();
var month = today.getMonth() - birthDate.getMonth();
if (month < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
if(CalAge() >= 21) {
alert("You are over 21!");
}
if(CalAge() < 21) {
alert("You are under 21!");
}
</script>
</head>
<body >
<input type="text" name="age" size="30" onClick="Calage()" placeholder="Enter your age" />
<br />
<input type="button" onclick="CalAge()" value="SUBMIT Age">
<input type="reset" onclick="CalAge()" value="Reset age">
</html>
最佳答案
如果用户输入的是他们的年龄(不是他们的生日),那么就不需要计算年龄。你可以这样做:
const btnCalcAge = document.querySelector('#btn-calc-age');
const btnReset = document.querySelector('#btn-reset');
const txtAge = document.querySelector('#txt-age');
const MIN_AGE = 21;
btnCalcAge.addEventListener('click', function(e) {
const age = parseInt(txtAge.value, 10);
if (age < MIN_AGE) {
window.location.href = 'http://www.disney.com';
return;
}
console.log('Welcome adult!');
});
btnReset.addEventListener('click', function(e) {
txtAge.value = "";
});
<input id="txt-age" type="text" name="age" size="30" placeholder="Enter your age" />
<br />
<input id="btn-calc-age" type="button" value="SUBMIT Age" />
<input id="btn-reset" type="reset" value="Reset age" />
关于javascript - 如何将函数链接到 JavaScript 中的 HTML 按钮和文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759038/