输入中的ValueChange事件

时间:2017-01-13 19:04:46

标签: javascript html events

<input type='number' id='number1'/>

这是我输入数字以便稍后对它们进行操作(加起来等)的地方。我已经掩盖了这一部分,但我希望将其扩展为删除<span id='total'></span>中存储的总数,只要在<input/>中写入新内容即可。 首先,我尝试了addEventListener('input', function());,但问题是,它甚至可以在未注册的输入上运行。所以,因为我有<input type='number'/>如果我写'abcd'等没有任何变化,但是总数被清除,因为它触发了'input' event listener。所以我做了一些挖掘,找到了ValueChange事件监听器,但是我无法使它工作(但input的值明显改变了。)

说实话,我检查了解决方案,并且回复是关于jQuery或一些解决方法。

代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Kalkulator-JS</title>
        <script>
            function operation(x) {
                var typeOfOp = x;
                var n1 = document.getElementById('number1').value;
                var n2 = document.getElementById('number2').value;
                var total = '';
                console.log('Type of operation: ' + typeOfOp);
                console.log('Number 1: ' + n1);
                console.log('Number 2: ' + n2);

                if (isNumber(n1)==false || isNumber(n2)==false) {
                    alert('Input right data');
                    return false;
                }
                n1 = Number(n1);
                n2 = Number(n2);

                switch (typeOfOp) {
                    case '+':
                        total = (n1 + n2);
                        break;
                    case '-':
                        total = (n1 - n2);
                        break;
                    case '*':
                        total = (n1 * n2);
                        break;
                    case '/':
                        if (n2 == 0) {
                            alert("You can't divide by 0!!!");
                            czysczenie();
                            return false;
                        }
                        total = (n1 / n2);
                }
                document.getElementById('total').innerHTML = total;
            }

            function isNumber(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
            }

            function cleanup() {
                document.getElementById('total').innerHTML = '';
            }

            document.addEventListener('DOMContentLoaded', function() {
                var sum = document.getElementById('sum');
                var subtract = document.getElementById('subtract');
                var multiply = document.getElementById('multiply');
                var divide = document.getElementById('divide');
                sum.addEventListener('click', function() {
                    operation(sum.value);
                });
                subtract.addEventListener('click', function() {
                    operation(subtract.value);
                });
                multiply.addEventListener('click', function() {
                    operation(multiply.value);
                });
                divide.addEventListener('click', function() {
                    operation(divide.value);
                });
                document.getElementById('number1').addEventListener('input', function() {
                    cleanup();
                });
            });


        </script>
    </head>
    <body>
        <table>
            <tr>
                <td>Number 1</td>
                <td>Number2</td>
            </tr>
            <tr>
                <td><input type='number' id='number1'/></td>
                <td><input type='number' id='number2'/></td>
            </tr>
        </table>
        <input type='button' id='sum' value='+'/>
        <input type='button' id='subtract' value='-'/>
        <input type='button' id='multiply' value='*'/>
        <input type='button' id='divide' value='/'/>
        <div id='text'>
            Total: <span id='total'></span>
        </div>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

如果我理解正确,我相信你想要的是addEventListener('keydown', function())。像这样:

document.getElementById('liczba1').addEventListener('keydown', function(e) {
   if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
});

<强>解释

使用事件监听器时,会将Event对象传递给函数,为您提供有关已发生事件的信息。在这种情况下,keydown事件对象具有关于已按下该键的信息。

完整代码示例:

function dzialanie(x) {
  var typDzialania = x;
  var n1 = document.getElementById('liczba1').value;
  var n2 = document.getElementById('liczba2').value;
  var wynik = '';
  console.log('Typ dzialania: ' + typDzialania);
  console.log('Liczba 1: ' + n1);
  console.log('Liczba 2: ' + n2);

  if (isNumber(n1) == false || isNumber(n2) == false) {
    alert('Wprowadź poprawne dane');
    return false;
  }
  n1 = Number(n1);
  n2 = Number(n2);

  switch (typDzialania) {
    case '+':
      wynik = (n1 + n2);
      break;
    case '-':
      wynik = (n1 - n2);
      break;
    case '*':
      wynik = (n1 * n2);
      break;
    case '/':
      if (n2 == 0) {
        alert('Nie dziel przez 0!!!');
        czysczenie();
        return false;
      }
      wynik = (n1 / n2);
  }
  document.getElementById('wynik').innerHTML = wynik;
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function czyszczenie() {
  document.getElementById('wynik').innerHTML = '';
}

document.addEventListener('DOMContentLoaded', function() {
  var dodawanie = document.getElementById('dodawanie');
  var odejmowanie = document.getElementById('odejmowanie');
  var mnozenie = document.getElementById('mnozenie');
  var dzielenie = document.getElementById('dzielenie');
  dodawanie.addEventListener('click', function() {
    dzialanie(dodawanie.value);
  });
  odejmowanie.addEventListener('click', function() {
    dzialanie(odejmowanie.value);
  });
  mnozenie.addEventListener('click', function() {
    dzialanie(mnozenie.value);
  });
  dzielenie.addEventListener('click', function() {
    dzialanie(dzielenie.value);
  });
  document.getElementById('liczba1').addEventListener('keydown', function(e) {
    if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
  });
  document.getElementById('liczba2').addEventListener('keydown', function(e) {
    if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
  });
});
<!DOCTYPE html>
<html>

<body>
  <table>

    <tr>
      <td>Liczba 1</td>
      <td>Liczba 2</td>
    </tr>
    <tr>
      <td>
        <input type='number' id='liczba1' />
      </td>
      <td>
        <input type='number' id='liczba2' />
      </td>
    </tr>
  </table>
  <input type='button' id='dodawanie' value='+' />
  <input type='button' id='odejmowanie' value='-' />
  <input type='button' id='mnozenie' value='*' />
  <input type='button' id='dzielenie' value='/' />
  <div id='tekst'>
    Wynik: <span id='wynik'></span>
  </div>
</body>

</html>

答案 1 :(得分:0)

解决方案,感谢@Teemu和@imtheman之间的讨论,非常感谢!

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Kalkulator-JS</title>
        <script>
            function operation(x) {
                var typeOfOp = x;
                var n1 = document.getElementById('number1').value;
                var n2 = document.getElementById('number2').value;
                var total = '';
                console.log('Type of operation: ' + typeOfOp);
                console.log('Number 1: ' + n1);
                console.log('Number 2: ' + n2);

                if (isNumber(n1)==false || isNumber(n2)==false) {
                    alert('Input right data');
                    return false;
                }
                n1 = Number(n1);
                n2 = Number(n2);

                switch (typeOfOp) {
                    case '+':
                        total = (n1 + n2);
                        break;
                    case '-':
                        total = (n1 - n2);
                        break;
                    case '*':
                        total = (n1 * n2);
                        break;
                    case '/':
                        if (n2 == 0) {
                            alert("You can't divide by 0!!!");
                            czysczenie();
                            return false;
                        }
                        total = (n1 / n2);
                }
                document.getElementById('total').innerHTML = total;
            }

            function isNumber(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
            }

            function cleanup() {
                document.getElementById('total').innerHTML = '';
            }

            document.addEventListener('DOMContentLoaded', function() {
                var sum = document.getElementById('sum');
                var subtract = document.getElementById('subtract');
                var multiply = document.getElementById('multiply');
                var divide = document.getElementById('divide');
                sum.addEventListener('click', function() {
                    operation(sum.value);
                });
                subtract.addEventListener('click', function() {
                    operation(subtract.value);
                });
                multiply.addEventListener('click', function() {
                    operation(multiply.value);
                });
                divide.addEventListener('click', function() {
                    operation(divide.value);
                });
                document.getElementById('number1').addEventListener('keydown', function(e) {
                    if (isNumber(e.key)) {
                        cleanup();
                    }
                });
            });


        </script>
    </head>
    <body>
        <table>
            <tr>
                <td>Number 1</td>
                <td>Number2</td>
            </tr>
            <tr>
                <td><input type='number' id='number1'/></td>
                <td><input type='number' id='number2'/></td>
            </tr>
        </table>
        <input type='button' id='sum' value='+'/>
        <input type='button' id='subtract' value='-'/>
        <input type='button' id='multiply' value='*'/>
        <input type='button' id='divide' value='/'/>
        <div id='text'>
            Total: <span id='total'></span>
        </div>
    </body>
</html>

说明:

  1. 我第一次咬它,ValueChange没用,因为它是XUL(不知道它现在是什么,但它没用),必须使用与DOM相关的东西
  2. 我必须使用之前尝试过的一个事件监听器(keydown / input),但过滤结果
  3. 我使用对象很糟糕,而且keydown事件对象比输入对象更容易理解(更简单)
  4. e.key(或event.key)为我提供了事件的关键属性值
  5. 所以现在我们需要验证按下的键是否为数字。
  6. 但我们不能使用Number()的内置函数,因为空插槽,如Number(''),等于0
  7. 所以我创建了自己的函数isNumber。瞧。