【发布时间】:2023-11-26 10:34:01
【问题描述】:
我正在尝试创建一个实时年龄计数器,它使用 setInterval() 每秒计算和更新年龄。它适用于预定义的输入,但不适用于通过日期对象提交的手动用户输入。如何将“日期”类型的输入传递给我正在使用的 calculateAge() 函数。
//js file
function ageCalculator() {
function startCal() {
setInterval( function() {
calculateAge();
}, 1000);
}
function calculateAge() {
var nowDate = new Date();
// Example date of birth.
var dob = document.getElementById("age-value");
var dobDate = new Date(dob);
var str = (years +":"+months+":"+weeks+":"+days+":"+hours+":"+minutes+":"+seconds);
document.getElementById("age").innerHTML = str;
}
return {
startCal : startCal
}
}
var ageCalculatorInstance = ageCalculator();
//ageCalculatorInstance.startCal();
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age calculator</title>
</head>
<body>
<div class="container">
<header>
<h1>Age calculator</h1>
</header>
<div class="input-age">
<label for="age-value">Enter your age</label>
<input id="age-value" type="date" />
<button type="submit" onclick="function startCal()">Calculate Age</button>
</div>
<div id="age">
</div>
</div>
<script src='js/script.js'></script>
</body>
</html>
【问题讨论】:
-
可以使用 document.getElementById('age-value').value 获取用户输入的数据
-
另外,这是调用函数的正确方法吗?
var form = document.getElementById('submit-form'); form.button.onclick() = function() { ageCalculatorInstance.startCal(); } -
你不应该在调用中只使用方法名的关键字function。 onclick="method()"
标签: javascript html date input calculator