ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで その14

Chapter 6 HTML や XML の文書を操作する - DOM (Document Object Model) -

イベントハンドラーを取り除く

追加したイベントハンドラーを無効にするには、null を指定すれば良いです。

html
<html>
<head>
</head>
<body>
  <form>
    <input id="btn" type="button" value="ダイアログ表示">
  </form>
  <script type="text/javascript" src="../js/sample14.js"></script>
</body>
</html>
sample14.js
window.onload = function() {
  var btn = document.getElementById('btn');
  
  btn.onclick = function() {
    window.alert('おはようございます');
    btn.onclick = null;
    
  };

}

イベントオブジェクト

イベントリスナーに引数を指定して、イベントオブジェクトを受け取ります。

html
<html>
<head>
</head>
<body>
  <form>
    <input id="btn" type="button" value="クリック">
  </form>
  <script type="text/javascript" src="../js/sample15.js"></script>
</body>
</html>
sample15.js
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('btn').addEventListener('click', function(e) {
    var target = e.target;
    console.log("発生元: " + target.nodeName + "/" + target.id);
    console.log("種類: " + e.type);
  }, false);
}, false);