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

回答編集履歴

1

jsでmapにアクセスするところのサンプル追加

2020/07/27 08:03

投稿

YakumoSaki
YakumoSaki

スコア2027

answer CHANGED
@@ -7,26 +7,40 @@
7
7
  th:inline〜をつけると、以下の様な出力になり、Javascriptとして扱えるようになります。
8
8
  `const mapObj = {"":"0","\u3068\u308A":"2","\u3046\u3057":"3","\u3055\u304B\u306A":"1"};`
9
9
 
10
-
11
-
12
10
  ```html
13
11
  <!DOCTYPE html>
14
12
  <html>
15
13
  <head>
16
- <script th:inline="javascript">
17
- const mapObj = /*[[${slctTypeMap}]]*/ null;
18
-
19
- console.log(mapObj);
20
- </script>
21
14
  </head>
22
15
  <body>
23
- // MAPを使ってプルダウンを表示しています。これはうまくいきます。
24
16
  <ul>
17
+ <li>
25
- <li><select id="slctType" name="slctType">
18
+ <select id="slctType" name="slctType">
26
19
  <option value="">------------</option>
27
20
  <option th:each="mp : ${slctTypeMap}" th:value="${mp.value}" th:inline="text">
21
+ [[${mp.key}]]
28
- [[${mp.key}]]</option></select></li>
22
+ </option></select>
23
+ </li>
24
+
25
+ <li>
26
+ <select id="by_js" name="selectType">
27
+ </select>
28
+ </li>
29
+
29
30
  </ul>
31
+ <script th:inline="javascript">
32
+ const mapObj = /*[[${slctTypeMap}]]*/ null;
33
+
34
+ const selectElement = document.getElementById("by_js");
35
+
36
+ for (let key in mapObj) {
37
+ console.log("selectに追加します -> " + "key:" + key + " value:" + mapObj[key]);
38
+ let option = document.createElement("option");
39
+ option.text = key;
40
+ option.value = mapObj[key];
41
+ selectElement.appendChild(option);
42
+ }
43
+ </script>
30
44
  </body>
31
45
  </html>
32
46
  ```