[英]How to pass input value of type 'date' to a function which Calculates and updates age every second
我正在尝试创建一个实时年龄计数器,它使用 setInterval() 每秒计算和更新年龄。 它适用于预定义的输入,但不适用于通过日期 object 提交的手动用户输入。 如何将“日期”类型的输入传递给我正在使用的 calculateAge() function。
//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>
这应该为您提供用户输入的日期:
const input = document.getElementById("age-value").value;
const dateEntered = new Date(input);
使用 document.getElementById("age-value")。 value
并将 function 称为onclick="ageCalculatorInstance.startCal()"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.