用javascript计算出生年份

时间:2017-11-30 23:06:53

标签: javascript html css

我试图计算任何年龄的出生年份,但我不能这样做。 我没有看到任何错误,计算功能正常,但它没有输出任何值。我认为错误在于计算功能..



<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>BirthDate</title>
  <link rel="stylesheet" type="text/css" href="style.css">

</head>

<body style="background-color: #bfc5c5">
  <form style="margin-top:10px">
    <input type="number" name="number" style="height:30px;width: 400px;padding-left: 10px" placeholder="type your age" id="number">
    <input type="button" value="find year" id="button" style="height: 35px">
    <p id="year">year</p>
  </form>

  <script type="text/javascript">
    function calculate() {
      var number = document.getElementById("number").value;

      if (number == "" || number == 0) {
        window.alert("Please type your correct age!");
        return;
      }

      var date = new(Date()).getFullYear()
      var birthyear = number - date;

      document.getElementById("year").style.display = "block";
      document.getElementById("year").innerHTML = "Your Birth Year is " + birthyear;

    }

    document.getElementById("year").style.display = "none";
    document.getElementById("button").onclick = function {
      calculate();
    };
  </script>

</body>

</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您要从括号中包含的Date构造函数中遗漏new

var date = (new Date()).getFullYear();

错过了onClick事件处理程序的一组括号:

document.getElementById("button").onclick = function() {...}

答案 1 :(得分:1)

您的代码中有两个错误,当您修复它们时,一切顺利:

  1. 功能错过了括号()

     document.getElementById("button").onclick = function  {
     ____________________________________________________^^
    

    应该是:

     document.getElementById("button").onclick = function() {
    
  2. 您的日期定义在:

    中有额外的括号()
    var date = new(Date()).getFullYear();
    ______________^______^
    

    应该是:

    var date = new Date().getFullYear();
    
  3. 希望这有帮助。

    工作片段:

    &#13;
    &#13;
    function calculate() {
      var number = document.getElementById("number").value;
    
      if (number == "" || number == 0) {
        window.alert("Please type your correct age!");
        return;
      }
    
      var date = new Date().getFullYear()
      var birthyear = number - date;
    
      document.getElementById("year").style.display = "block";
      document.getElementById("year").innerHTML = "Your Birth Year is " + birthyear;
    }
    
    
    document.getElementById("year").style.display = "none";
    document.getElementById("button").onclick = function() {
      calculate();
    };
    &#13;
    body {
      background-color: #bfc5c5;
    }
    &#13;
    <form style="margin-top:10px">
      <input type="number" name="number" style="height:30px;width: 400px;padding-left: 10px" placeholder="type your age" id="number">
      <input type="button" value="find year" id="button" style="height: 35px">
      <p id="year">year</p>
    </form>
    &#13;
    &#13;
    &#13;