teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

handleEventのコード追記

2016/10/29 05:42

投稿

think49
think49

スコア18194

answer CHANGED
@@ -1,25 +1,43 @@
1
1
  複数の機能間でデータを共有する方法は handleEvent, data-*属性、カスタムイベント、WeakMap 等があります。
2
- ご掲示のコードでは私なら `handleEvent` を使いますね。
3
2
 
3
+ ### handleEvent
4
+
4
5
  ```HTML
5
6
  <div class="demo">
6
- <ul>
7
+ <ul>
7
- <li id="list1">list1</li>
8
+ <li id="list1">list1</li>
8
- <li id="list2">list2</li>
9
+ <li id="list2">list2</li>
9
- <li id="list3">list3</li>
10
+ <li id="list3">list3</li>
10
- </ul>
11
+ </ul>
11
- <button type="button" id="button">Button</button>
12
+ <button type="button" id="button">Button</button>
12
13
  </div>
13
14
  <script>
14
15
  'use strict';
15
- document.querySelector('demo').addEventListener('click', {
16
+ document.querySelector('.demo').addEventListener('click', {
16
17
  text: '',
17
- function handleClick (event) {
18
+ handleEvent: function handleClick (event) {
18
19
  var target = event.target;
20
+
21
+ if (target.tagName === 'LI') {
22
+ this.text = target.firstChild.data;
23
+ } else if (target.id === 'button') {
19
- // ほげほげ(後で書きます)
24
+ console.log(this.text);
25
+ }
20
26
  }
21
27
  }, false);
22
28
  </script>
23
29
  ```
24
30
 
31
+ ### data-*属性
32
+
33
+ 要追記。
34
+
35
+ ### WeakMap
36
+
37
+ 要追記。
38
+
39
+ ### カスタムイベント
40
+
41
+ 要追記。
42
+
25
43
  Re: kerokero335 さん