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

回答編集履歴

2

調整

2018/10/01 01:28

投稿

yambejp
yambejp

スコア117919

answer CHANGED
@@ -31,11 +31,13 @@
31
31
  x.addEventListener('click',function(){
32
32
  var len=document.querySelectorAll('#inputArea input').length;
33
33
  var node=document.querySelector('#inputArea input:last-of-type');
34
+ var xid=x.getAttribute('id');
35
+ var area=document.querySelector('#inputArea');
34
- if(x.getAttribute('id')==="add" && len<5){
36
+ if(xid==="add" && len<5){
35
- document.querySelector('#inputArea').insertBefore(node.cloneNode(),node.nextSibling);
37
+ area.insertBefore(node.cloneNode(),node.nextSibling);
36
38
  }
37
- if(x.getAttribute('id')==="del" && len>1){
39
+ if(xid==="del" && len>1){
38
- document.querySelector('#inputArea').removeChild(node);
40
+ area.removeChild(node);
39
41
  }
40
42
  });
41
43
  });

1

蛇足

2018/10/01 01:28

投稿

yambejp
yambejp

スコア117919

answer CHANGED
@@ -1,14 +1,14 @@
1
1
  こんな感じですがnameをつけないとsubmitしても無効なのでもうすこし詰めたほうがよいでしょう
2
2
  ```javascript
3
3
  <script>
4
- window.addEventListener('DOMContentLoaded', function(e){
4
+ window.addEventListener('DOMContentLoaded', function(){
5
- document.querySelector('#add').addEventListener('click',function(e){
5
+ document.querySelector('#add').addEventListener('click',function(){
6
6
  if(document.querySelectorAll('#inputArea input').length<5){;
7
7
  var l=document.querySelector('#inputArea input:last-of-type');
8
8
  document.querySelector('#inputArea').insertBefore(l.cloneNode(),l.nextSibling);
9
9
  }
10
10
  });
11
- document.querySelector('#del').addEventListener('click',function(e){
11
+ document.querySelector('#del').addEventListener('click',function(){
12
12
  if(document.querySelectorAll('#inputArea input').length>1){;
13
13
  var l=document.querySelector('#inputArea input:last-of-type');
14
14
  document.querySelector('#inputArea').removeChild(l);
@@ -21,4 +21,29 @@
21
21
  <button id="add">+</button>
22
22
  <button id="del">-</button>
23
23
  </div>
24
+ ```
25
+ # 蛇足
26
+ 共通部分があるのでまとめられるかなぁと思ったらイマイチ効率化できなかったソース
27
+ ```javascript
28
+ <script>
29
+ window.addEventListener('DOMContentLoaded', function(){
30
+ [].forEach.call(document.querySelectorAll('#add,#del'),function(x){
31
+ x.addEventListener('click',function(){
32
+ var len=document.querySelectorAll('#inputArea input').length;
33
+ var node=document.querySelector('#inputArea input:last-of-type');
34
+ if(x.getAttribute('id')==="add" && len<5){
35
+ document.querySelector('#inputArea').insertBefore(node.cloneNode(),node.nextSibling);
36
+ }
37
+ if(x.getAttribute('id')==="del" && len>1){
38
+ document.querySelector('#inputArea').removeChild(node);
39
+ }
40
+ });
41
+ });
42
+ });
43
+ </script>
44
+ <div id="inputArea">
45
+ <input type="text" maxlength="80">
46
+ <button id="add">+</button>
47
+ <button id="del">-</button>
48
+ </div>
24
49
  ```