简体   繁体   English

如何将“日期”类型的输入值传递给每秒计算和更新年龄的 function

[英]How to pass input value of type 'date' to a function which Calculates and updates age every second

I'm trying to create a live age counter which calculates & updates the age every second using setInterval().我正在尝试创建一个实时年龄计数器,它使用 setInterval() 每秒计算和更新年龄。 It works with the predefined input but isn't working with the manual user input submitted through a date object.它适用于预定义的输入,但不适用于通过日期 object 提交的手动用户输入。 How to pass the input of type 'date' to the calculateAge() function I'm using.如何将“日期”类型的输入传递给我正在使用的 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 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>

This should give you the date entered by the user:这应该为您提供用户输入的日期:

const input = document.getElementById("age-value").value;
const dateEntered = new Date(input);

Use document.getElementById("age-value").使用 document.getElementById("age-value")。 value

and call the function as onclick="ageCalculatorInstance.startCal()"并将 function 称为onclick="ageCalculatorInstance.startCal()"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM