回答編集履歴

3

リファクタリング

2022/10/06 16:04

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -7,7 +7,7 @@
7
7
  また、mouseoverとmouseoutの時の処理内容がほぼ同じなので、1つの関数でどちらも対応できるようifで分岐させてみました。
8
8
 
9
9
  ### コード例
10
- - 動作確認用サンプル:https://jsfiddle.net/ox6upvy8/1/
10
+ - 動作確認用サンプル:https://jsfiddle.net/ox6upvy8/2/
11
11
  ```html
12
12
  <div class="sectionContainer">
13
13
  <div class="imgParent">
@@ -50,8 +50,11 @@
50
50
  const btns = document.getElementsByClassName('scrollBtn');
51
51
 
52
52
  // それぞれのボタンにホバー時とホバー解除時のイベントを設定
53
+ [...btns].forEach(btn => {
53
- [...btns].forEach(btn => btn.addEventListener('mouseover', changeScale));
54
+ btn.addEventListener('mouseover', changeScale);
54
- [...btns].forEach(btn => btn.addEventListener('mouseout', changeScale));
55
+ btn.addEventListener('mouseout', changeScale);
56
+ }
57
+ );
55
58
 
56
59
  // 画像を拡大・元のサイズに戻す関数
57
60
  function changeScale(e) {

2

this解説のコードにコメント追加

2022/10/06 16:00

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -81,10 +81,16 @@
81
81
  [...btns].forEach(btn => btn.addEventListener('click', whichElement));
82
82
 
83
83
  function whichElement(event) {
84
+ // イベント情報
84
- console.log(event); // イベント情報
85
+ console.log(event); // PointerEvent{...}
86
+
87
+ // イベントの発生した要素
85
- console.log(event.target); // イベントが発生した要素
88
+ console.log(event.target); // <a href="#">button 1</a>など
89
+
86
- console.log(event.currentTarget); // イベント登録した要素
90
+ // イベント登録されている要素
91
+ console.log(event.currentTarget); // <div class="btn"><a href="#">button 1</a></div>など
87
92
  }
93
+
88
94
  ```
89
95
 
90
96
  `addEventListener()`でイベントが発生すると、呼び出されたコールバック関数の引数には、自動的に発生したイベント情報が渡されます。

1

thisじゃなくて

2022/10/06 15:53

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -66,3 +66,29 @@
66
66
  }
67
67
  }
68
68
  ```
69
+
70
+ ### thisじゃなくて…
71
+ ちなみに、`addEventListener(イベントの種類, コールバック関数)`でイベントが発生した要素を取得する方法は`this`ではありません。
72
+
73
+ 例)
74
+ ```html
75
+ <div class="btn"><a href="#">button 1</a></div>
76
+ <div class="btn"><a href="#">button 2</a></div>
77
+ <div class="btn"><a href="#">button 3</a></div>
78
+ ```
79
+ ```javascript
80
+ const btns = document.getElementsByClassName('btn');
81
+ [...btns].forEach(btn => btn.addEventListener('click', whichElement));
82
+
83
+ function whichElement(event) {
84
+ console.log(event); // イベント情報
85
+ console.log(event.target); // イベントが発生した要素
86
+ console.log(event.currentTarget); // イベントを登録した要素
87
+ }
88
+ ```
89
+
90
+ `addEventListener()`でイベントが発生すると、呼び出されたコールバック関数の引数には、自動的に発生したイベント情報が渡されます。
91
+ ですのでコールバック関数の引数の中には分かりやすくするため`function myFunction(e)`とか`function myFunction(event)`などと書かれます。
92
+ - `event`で、発生したイベント情報を全て取得でき、
93
+ - `event.target`で、`event`の情報の中にある、イベントが発生した実際の要素を取得でき、
94
+ - `event.currentTarget`で、`event`の情報の中にある、発生したイベントを登録しておいた要素が取得できます。