LoginSignup
21
34

More than 3 years have passed since last update.

function(e)を使ってみる

Last updated at Posted at 2015-02-04

宿題
↓を実行してクリックした対象のconstructorがHTMLDivElementのときにconsole.log("success");を実行する

js
document.body.addEventListener("click", function (e) {
  // -- 解答ここから  

  // -- ここまで
  e.preventDefault();
  e.returnValue = true;
});

eはeventのe

function(e) この引数eは、eventの「e」

イベントハンドラにはイベントオブジェクトが渡される
https://developer.mozilla.org/ja/docs/Learn/JavaScript/Building_blocks/Events

firebugなどのコンソールでconsole.log(e)してDOMのプロパティ調査などで色々見るといい。
色々応用できそうな気分になれます。


解答例
(今回はe.target.tagNameを使用)

js
document.body.addEventListener("click", function (e) {
  // -- 解答ここから
  if ( e.target.tagName == "DIV" ) {
    console.log("success");
  }else{
    console.log("failed");
  }
  // -- ここまで
  e.preventDefault();
  e.returnValue = true;
});
21
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
34