2013-10-11 4 views
0

이 코드는 자바 스크립트에서 루프로 바꿀 수 있습니까? 자바에 새로운 학습자를 도와 주셔서 감사합니다!자바 스크립트 루핑 (foreach 또는 각각 사용)

HTML :

<div class="uploadBox"><input id="files3" class="upload" style="position:absolute;" placeholder="Upload Photo"/><input type="file" style="position:absolute;width:200px;height:44px;opacity:0;" id="selector3"/></div> 
<div id="checkBox3" class="checkBox"><img src="images/check.png"></div> 

자바 스크립트 :

document.getElementById("selector1").addEventListener("change",function(){ 
    document.getElementById("files1").value= 
     document.getElementById("selector1").files[0].name; 
    $('#checkBox1').css({'display': 'block'}); 
}); 

document.getElementById("selector2").addEventListener("change",function(){ 
    document.getElementById("files2").value= 
     document.getElementById("selector2").files[0].name; 
    $('#checkBox2').css({'display': 'block'}); 
}); 

document.getElementById("selector3").addEventListener("change",function(){ 
    document.getElementById("files3").value= 
     document.getElementById("selector3").files[0].name; 
    $('#checkBox3').css({'display': 'block'}); 
}); 
+0

우리는 또한 당신의 HTML 코드를 참조 할 필요가있다. 당신은 당신의 코드에서 jQuery를 가지고 있고, jQuery는 또한'.each()'메서드를 가지고 있습니다 ... – Sergio

+0

@Sergio 제 HTML을 추가했습니다! 답장을 보내 주셔서 감사합니다 – youaremysunshine

+0

그 두 divs 부모 div가 무엇입니까? – Sergio

답변

1

당신이 뭔가를 의미?

$('input[id^=selector]').each(function(){ 
    this.parent().next('div[class="checkBox"]').css({'display': 'block'}); 
    this.prev().val(this.files[0].name); 
}); 
+0

그냥 같은 대답을 쓰고 있었다 –

+0

내 코드에서 파일을 선택한 후 입력 상자에 파일 이름이 표시되지만 입력 상자에 파일 이름이 표시되지 않는다 – youaremysunshine

0

// 난 당신이 당신이

for (var i = 1; i < 3; i++) { 
    document.getElementById("selector"+i.toString()).addEventListener("change",function(){ 
    document.getElementById("files"+i.toString()).value= 
     document.getElementById("selector"+i.toString()).files[0].name; 
    $('#checkBox'+i.toString()).css({'display': 'block'}); 
}); 
} 
+0

코드에서 파일을 선택한 후 입력 상자에 파일 이름을 표시하지만 입력 상자에 파일 이름이 표시되지 않습니다. – youaremysunshine

0

이 시도 할 = 더를 줄 수있는 3 사용하지 않은 selector (closure를 잊지 마라!).

그리고 더 가독성을 위해 jQuery를 자바 스크립트를 혼합하지 낫다는 :

var n = 3 
for (var i = 1; i <= n; i++) { 
    $("selector" + i).on("change", (function (i) { 
     return function() { 
      $("files" + i).val($("selector" + i).get(0).files[0].name); 
      $("#checkBox" + i).css({ 
       "display": "block" 
      }); 
     } 
    })(i)); 
} 
0

예쁜 기본 : 루프의 사용 인덱스가를 연결하는

for (i = 1; i < 4; i++) { 
    document.getElementById("selector" + i).addEventListener("change",function(){ 
     document.getElementById("files" + i).value= 
      document.getElementById("selector" +i).files[0].name; 
     $('#checkBox' + i).css({'display': 'block'}); 
    }); 
} 
+0

코드에서 입력 상자에 파일 이름이 표시되면 입력 상자에 파일 이름이 표시됩니다. – youaremysunshine

관련 문제