繁体   English   中英

如何将函数链接到 JavaScript 中的 HTML 按钮和文本字段

[英]How to link the function to the HTML button and textfield in JavaScript

我被要求创建一个网页,用户插入年龄并获取一些消息。 如果用户未满 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 重定向到另一个链接。
如上面的答案所述,您可以使用下面提到的两个选项中的任何一个进行重定向:

if(calAge() >= 21) {
    window.location.replace("http://www.disney.com");
}

您也可以使用window.location.href来实现相同的目的。 但是,我强烈建议您阅读上面提到的答案,以更清楚地了解最适合您的情况。

这里有一些代码可以帮助你......

 const ageInput = document.querySelector('#age-input'); ageInput.valueAsDate = new Date(); document.querySelector('#Bt-Submit').onclick = function() { let Age = new Date( new Date() - ageInput.valueAsDate ).getFullYear() - 1970; console.log(Age); if ( Age < 21 ) { document.location.href = "https://disney.com" } } document.querySelector('#Bt-Reset').onclick = function() { ageInput.valueAsDate = new Date(); }
 <label>birth date : <input type="date" id="age-input" size="30" /> </label> <br /> <button id="Bt-Submit">SUBMIT Age</button> <button id="Bt-Reset">Reset Age</button>

暂无
暂无

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

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