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

回答編集履歴

2

修正

2019/01/17 06:48

投稿

papinianus
papinianus

スコア12705

answer CHANGED
@@ -8,18 +8,36 @@
8
8
  // カレンダーの表示
9
9
  var wrapper = document.getElementById('calendar');
10
10
  add_calendar(wrapper, year, month);
11
+ }
11
12
 
13
+ function handler(e) {
14
+ if(e.target.innerText === "") return;
15
+ const yearmonth = document.querySelector(".calendar-header__title").innerText;
16
+ document.querySelector("input").value = yearmonth + e.target.innerText + "日";
17
+ }
18
+ /**
19
+ * 指定した年月のカレンダーを表示する
20
+ * @param {object} wrapper - カレンダーを追加する親要素
21
+ * @param {number} year - 年の指定
22
+ * @param {number} month - 月の指定
23
+ */
24
+ function add_calendar(wrapper, year, month) {
25
+ // 現在カレンダーが追加されている場合は一旦削除する
26
+ wrapper.textContent = null;
27
+
28
+ // カレンダーに表示する内容を取得
29
+ var headData = generate_calendar_header(wrapper, year, month);
30
+ var bodyData = generate_month_calendar(year, month);
31
+
32
+ // カレンダーの要素を追加
33
+ wrapper.appendChild(headData);
34
+ wrapper.appendChild(bodyData);
12
35
  document.querySelectorAll("td").forEach(function (target) {
13
36
  // 引数targetにはdiv要素が1つずつ渡されている
14
37
  target.addEventListener('click', handler);
15
38
  });
16
39
  }
17
40
 
18
- function handler(e) {
19
- if(e.target.innerText === "") return;
20
- const yearmonth = document.querySelector(".calendar-header__title").innerText;
21
- document.querySelector("input").value = yearmonth + e.target.innerText + "日";
22
- }
23
41
  ```
24
42
  いちおうこう書いたものの、カスタムデータ属性などを使って、inputに設定したい値をtdにもっておいたほうがいい気がします。
25
43
  (もちろん、年月を表示しているところから取ってもいいんですが)

1

修正

2019/01/17 06:48

投稿

papinianus
papinianus

スコア12705

answer CHANGED
@@ -9,18 +9,19 @@
9
9
  var wrapper = document.getElementById('calendar');
10
10
  add_calendar(wrapper, year, month);
11
11
 
12
- /* こういうイベントリスナを設定しましょう */
13
12
  document.querySelectorAll("td").forEach(function (target) {
13
+ // 引数targetにはdiv要素が1つずつ渡されている
14
14
  target.addEventListener('click', handler);
15
15
  });
16
- /* */
17
16
  }
18
17
 
19
- /* handlerは、とりあえずログを出すだけです。「取得」の質問なので、inputへの設定は自分でできると想定 */
20
18
  function handler(e) {
21
19
  if(e.target.innerText === "") return;
22
- console.log(e.target.innerText);
20
+ const yearmonth = document.querySelector(".calendar-header__title").innerText;
21
+ document.querySelector("input").value = yearmonth + e.target.innerText + "日";
23
22
  }
24
23
  ```
25
24
  いちおうこう書いたものの、カスタムデータ属性などを使って、inputに設定したい値をtdにもっておいたほうがいい気がします。
26
- (もちろん、年月を表示しているところから取ってもいいんですが)
25
+ (もちろん、年月を表示しているところから取ってもいいんですが)
26
+
27
+ querySelectorを雑につかってるので、クラスとかタグ名とかで引かずにすむように、取りたい場所やセットしたい場所には適切なidを付与することを推奨します。