2013-10-11 49 views
0

可以將此代碼更改爲javascript中的循環嗎? 感謝您幫助我的新學習者javascript!javascript循環(使用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> 

的javascript:

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

是否有一個父div給那些2 div? – Sergio

回答

1

你的意思是這樣的嗎?

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

我只是寫了相同的答案 –

+0

在我的代碼中,在我選擇文件後,它將在輸入框中顯示文件名,但是這並沒有在輸入框中顯示文件名 – youaremysunshine

0

//我已經使用3你可以給沒有的時候,你要

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

試試這個:

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

非常基本的:循環使用索引來連接一個選擇器(不要忘記關閉!)。

而且最好是不要混淆的jQuery和JavaScript的更多可讀性:

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

在我的代碼中,在我選擇文件後,它將在輸入框中顯示文件名,但是這沒有在輸入框中顯示文件名 – youaremysunshine