【发布时间】:2016-11-10 02:18:09
【问题描述】:
这是我通过输入生日来计算一个人的年龄的代码。我在读取生日输入和在 getAge 函数中使用时遇到问题。我也无法在第二个文本字段中显示年龄。我不确定如何更正这些。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Age Calculator</title>
<script>
var birthday;
function getAge(birth) {
var bday = document.getElementById("bday");
var ageDisplay = document.getElementById("ageDisplay");
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year - birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year - birth_year - 1);
if (curr_month > birth_month) return parseInt(curr_year - birth_year);
if (curr_month < birth_month) return parseInt(curr_year - birth_year - 1);
}
var age = getAge(birthday);
ageDisplay.value = age
</script>
</head>
<body style="background-color:red">
<form>
<fieldset>
<label>Type your Date of Birth: </label>
<input type="text" id="bday" />
<input type="button" value="click me" onclick="getAge()" />
<br/>
<br/>
<label>Your Age is: </label>
<input type="text" id="ageDisplay" />
</fieldset>
</form>
<body>
</html>
【问题讨论】:
标签: javascript html button io