如何将javascript结果放入网页,因为值由于某种原因未定义

时间:2015-10-27 02:20:17

标签: javascript web

< script type = "text/javascript" >
  function myFunction() {
    var n1 = document.getElementById("form-control1").innerHTML;
    var n2 = document.getElementById("form-control2").innerHTML;

    return Math.max(n1, n2);
  };
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScript Challenge</title>


</head>

<body>
<!-- user interface -->
  First number
  <input type="text" id="form-control1" placeholder="your first number">Second number
  <input type="text" id="form-control2" placeholder="your second number">
  <br>
  <br>
  <button onclick="myFunction()">Calculate</button>

  </script>

</body>

</html>

我希望在变量n1和n2上分配用户输入值。之后,当单击按钮时,具有最大值的变量将显示在网页上。但目前价值似乎没有被存储,因为它说未定义。 我能做什么?任何帮助 提前致谢

2 个答案:

答案 0 :(得分:0)

将innerHTML字符串转换为整数:

return Math.max(parseInt(n1),parseInt(n2));

答案 1 :(得分:0)

尝试用.value替换.innerHTML input元素,以检索input元素的值;创建包含n1n2的数组,使用Number将值转换为Array.prototype.map(),添加output元素以将Math.max的结果打印到文档< / p>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JavaScript Challenge</title>
</head>
<body>
  <!-- user interface -->
  First number
  <input type="text" id="form-control1" placeholder="your first number">Second number
  <input type="text" id="form-control2" placeholder="your second number">
  <output></output>
  <br>
  <br>
  <button onclick="myFunction()">Calculate</button>
  <script type="text/javascript">
    function myFunction() {
      var n1 = document.getElementById("form-control1").value;
      var n2 = document.getElementById("form-control2").value;
      document.querySelector("output").innerHTML = Math.max.apply(Math, [n1, n2]);
    };
  </script>
</body>
</html>