提问者:小点点

自定义函数不从输入读取值


我正在尝试创建一个类似计算器的东西。我有一个自定义函数,它假设从两个变量加载输入值,并将它们放在一起,但它不起作用,所以我用控制台日志检查它是否加载了输入值,它所说的只是这些值未定义。你知道怎么解决这个问题吗?

let num1 = document.getElementById("number1").value,
    num2 = document.getElementById("number2").value,
    operator = document.getElementById("select"),
    resolutor = document.getElementById("resolute"),
    res = document.getElementById("result");

function mathoperation(num1, num2) {
    let value = operator.value,
        result;

    switch (value) {
        case "plus":
            console.log(num1); //console says unindefied
            console.log(num2); //console says unindefied
            break;
    }
}
<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.0">
      <title>Úloha 18.1</title>
  </head>
  <body>

      <input type="text" id="number1">
      
      <select name="" id="select">
          <option value="plus">+</option>
          <option value="minus">-</option>
          <option value="krat">*</option>
          <option value="deleno">/</option>
      </select>
      
      <input type="text" id="number2">
      <input type="button" id="resolute" value="=" onclick="mathoperation()">
      <input type="text" id="result" readonly>

  </body>
  </html>

共1个答案

匿名用户

您必须在事件处理程序内部而不是外部获取输入元素的值

  function mathoperation() {
    let num1 = document.getElementById("number1").value,
    num2 = document.getElementById("number2").value,
    operator = document.getElementById("select"),
    resolutor = document.getElementById("resolute"),
    res = document.getElementById("result");

           let value = operator.value,
           result;

           switch (value) {
            case "plus":
                console.log(num1); //console says unindefied
                console.log(num2); //console says unindefied
                break;

           }

  }
<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.0">
    <title>Úloha 18.1</title>
</head>
<body>

    <input type="text" id="number1">
    <select name="" id="select">
        <option value="plus">+</option>
        <option value="minus">-</option>
        <option value="krat">*</option>
        <option value="deleno">/</option>
    </select>
    <input type="text" id="number2">
    <input type="button" id="resolute" value="=" onclick="mathoperation()">
    <input type="text" id="result" readonly>
</body>
</html>