如何通过if / else语句在JavaScript中打印内容?

时间:2018-10-11 01:22:06

标签: javascript

对于旧版浏览器,我想添加一条if / else语句,显示“仅接受数字”,在这些浏览器中,您可以使用type=number在输入中添加字符串。

  var bttn = document.getElementById("agebttn");
  bttn.addEventListener("click", bttnClicked);

  function calculate(startingYear) {
    var dateObj = new Date()
    var currentYear = dateObj.getFullYear()
    return currentYear - startingYear;
  }

  function bttnClicked() {
    console.log("bttn clicked");
    var age = parseInt(document.getElementById('age').value);
    var yearsAlive = calculate(age);

    var html = "You entered " + age;
    html += "<br />You have been alive for " + yearsAlive + " years";
    document.getElementById('answer').innerHTML = html;
  }
<body>
  <h1>Age Calculator</h1>

  <input type="number" id="age" placeholder="Enter your birthyear">
  <input type="button" id="agebttn" value="Calc" />
  <div id="answer">

  </div>
</body>

2 个答案:

答案 0 :(得分:0)

您可以在此处使用isNaN函数检查是否可以解析int:

function bttnClicked() {
    console.log("bttn clicked");
    var age = parseInt(document.getElementById('age').value);

    if(isNaN(age)){
        document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
        return;
    }

    var yearsAlive = calculate(age);

    var html = "You entered " + age;
    html += "<br />You have been alive for " + yearsAlive + " years";
    document.getElementById('answer').innerHTML = html;
  }

答案 1 :(得分:0)

CMIIW

根据我的观察,您想将脚本逻辑的结果打印到您的 div标签ID =答案正确吗?而您只想输入数字?

您可能想使用!isNan(age)函数来验证您的输入,因此当他们验证并没有输入数字时,您会在其他情况下返回错误消息