单独的单击事件后如何触发警报

时间:2017-04-26 22:34:37

标签: javascript

我有一个带有4个输入框的表单。我想在点击任意两个方框后才触发警报。实现此目的的最简单方法是什么(仅使用Javascript,而不是jQuery)?

HTML

<input id="FieldOne">Field One</><br>
<input id="FieldTwo">Field Two</><br>
<input id="FieldThree">Field Three</><br>
<input id="FieldThree">Field Four

1 个答案:

答案 0 :(得分:-1)

只需在输入字段中添加addEventListener即可在每次点击时触发功能。

<script>
  const counter = 0;
  const fieldOne = document.getElementById('FieldOne').addEventListener("click", countUp);
  const fieldTwo = document.getElementById('FieldTwo').addEventListener("click", countUp);
  const fieldThree = document.getElementById('FieldThree').addEventListener("click", countUp);
  const fieldFour = document.getElementById('FieldFour').addEventListener("click", countUp);

  function countUp() {
    counter = counter + 1;
    if (counter === 2) {
      alert('You have clicked two inputs!');
    }
  }
</script>