首页 > 解决方案 > Javascript 天数 getElementbyID 问题

问题描述

我正在尝试完成“天数”项目,我的问题是在我的空盒子里得到结果。当通过 Chrome 进行检查时,我看不到我的结果,id="flex-box-result"所以结果也看不到。我做错了什么?在此先感谢Chrome 检查

// Challenge Your Age in Days with Prompt

function ageInDays() {
  var birthYear = prompt("What year were you born?");
  var ageInDaysMult = (2020 - birthYear) * 365;
  var h1 = document.createElement("h1");
  var textAnswer = document.createTextNode("You are " + ageInDaysMult + "days old");
  h1.setAttribute("id", "ageInDays");
  h1.appendChild(textAnswer);
  document.getElementById("flex-box-result").appendChild(h1);

}

function reset(){
  document.getElementById("ageInDays").remove();
}
h2 {
  align-items: center;
  text-align: center;
}

.container-1 {
    border: 1px solid black;
    width: 75%;
    margin: 0 auto;
}
.flex-box-container-1{
  display: flex;
  border: 1px solid black;
  flex-wrap: wrap;
  padding: 10px;
  flex-direction: row;
  justify-content: space-around;
}

.flex-box-container-1 div {
  display: flex;
  padding: 10px;
  border: 1px solid black;
  align-items: center;
}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title></title>
  </head>
  <body>
    <h2>Age in Days </h2>
    <div class="container-1">
    <div class="flex-box-container-1">
        <div>
          <button class="btn btn-primary" onclick="ageInDays()"> Click here </button>
        </div>
        <div>
          <button class="btn btn-danger" onclick="ageInDays()"> Reset </button>
        </div>


        <div class="flex-box-container-1">
          <div id="flex-box-result"></div>
        </div>
    </div>
  </div>
    <script type="text/javascript" src="java2.js">

    </script>
  </body>
</html>

标签: javascriptflexbox

解决方案


在您的重置按钮上,您必须放置重置功能而不是 ageInDays

<button class="btn btn-danger" onclick="ageInDays()"> Reset </button>

<button class="btn btn-danger" onclick="reset()"> Reset </button>

希望这可以帮助。


推荐阅读