从回调函数访问数据

时间:2016-08-16 23:50:36

标签: javascript

  let toggleForm = function() {
    // code here
  }

  document.getElementById('one').addEventListener("click", toggleForm, false);

  document.getElementById('two').addEventListener("click", toggleForm, false);

在toggleForm中我想知道元素一或二是否触发了事件。你会怎么做呢?

1 个答案:

答案 0 :(得分:2)

使用e.target

<button id = 'one'>One</button>
<button id = 'two'>Two</button>
<script>
  var one = document.getElementById('one'),
    two = document.getElementById('two');
  let toggleForm = function(e) {
    if (e.target === one) alert('One');
    else alert('Two');
  };
  one.addEventListener("click", toggleForm, false);
  two.addEventListener("click", toggleForm, false);
</script>