回答編集履歴

1

追記

2021/11/15 05:04

投稿

KAOsaka
KAOsaka

スコア531

test CHANGED
@@ -101,3 +101,139 @@
101
101
  </script>
102
102
 
103
103
  ```
104
+
105
+
106
+
107
+ ## 追記
108
+
109
+
110
+
111
+ > この処理は2回までとかもできるのでしょうか?
112
+
113
+ > 1を押し1個表示され5を押し5個表示され 3回目以降は押しても表示できなくなる感じです。
114
+
115
+
116
+
117
+ ボタンを押した回数をどこかに保存しておいて、画像追加処理の部分で判定してください。
118
+
119
+
120
+
121
+ - [デモ - JSFiddle](https://jsfiddle.net/v6qtpkLb/)
122
+
123
+
124
+
125
+ ``` html
126
+
127
+ <div id="basket" data-image-add-request-count="0"></div>
128
+
129
+
130
+
131
+ <template id="image-template">
132
+
133
+ <img src="https://via.placeholder.com/512/999999/333333/?text=Ringo" style="width: 40px; height: 40px;">
134
+
135
+ </template>
136
+
137
+
138
+
139
+ <button id="button1">
140
+
141
+ - 1 -
142
+
143
+ </button>
144
+
145
+
146
+
147
+ <button id="button5">
148
+
149
+ - 5 -
150
+
151
+ </button>
152
+
153
+
154
+
155
+ <script>
156
+
157
+ const basket = document.querySelector("#basket");
158
+
159
+ const imageTemplate = document.querySelector("#image-template");
160
+
161
+ const button1 = document.querySelector("#button1");
162
+
163
+ const button5 = document.querySelector("#button5");
164
+
165
+
166
+
167
+ const maxImageAddRequestCount = 2;
168
+
169
+
170
+
171
+ basket.addEventListener("App.ImageAddRequest", (event) => {
172
+
173
+ const imageAddRequestCount = Number.parseInt(basket.dataset.imageAddRequestCount);
174
+
175
+
176
+
177
+ if (imageAddRequestCount >= maxImageAddRequestCount) {
178
+
179
+ return;
180
+
181
+ }
182
+
183
+
184
+
185
+ const imageCount = event.detail.imageCount ?? 0;
186
+
187
+
188
+
189
+ for (let count = 0; count < imageCount; count++) {
190
+
191
+ const image = imageTemplate.content.cloneNode(true);
192
+
193
+
194
+
195
+ basket.appendChild(image);
196
+
197
+ }
198
+
199
+
200
+
201
+ basket.dataset.imageAddRequestCount = imageAddRequestCount + 1;
202
+
203
+ });
204
+
205
+
206
+
207
+ button1.addEventListener("click", (event) => {
208
+
209
+ basket.dispatchEvent(new CustomEvent("App.ImageAddRequest", {
210
+
211
+ detail: {
212
+
213
+ imageCount: 1,
214
+
215
+ },
216
+
217
+ }));
218
+
219
+ });
220
+
221
+
222
+
223
+ button5.addEventListener("click", (event) => {
224
+
225
+ basket.dispatchEvent(new CustomEvent("App.ImageAddRequest", {
226
+
227
+ detail: {
228
+
229
+ imageCount: 5,
230
+
231
+ },
232
+
233
+ }));
234
+
235
+ });
236
+
237
+ </script>
238
+
239
+ ```