2015-04-03 22 views
0

嗨在下面的代碼中,我將使用以下java腳本函數上傳圖像,以便第一個輸入工作正常。同樣,如何在第一個輸入字段時調用I我傳遞的ID有變化第一個和第二個圖像顯示相同。使用單個函數如何調用兩個不同的輸入字段

HTML

<div class="person_pic"> 
    <label>Please upload your photo</label><input type='file' name="image" onchange="readURL(this);" /> 
    <img id="blah" src="#" alt="your image" /> 
</div> 
<div class="person_pic"> 
    <label>Please upload your family photo</label> 
    <input type='file' name="image" onchange="readURL(this);" /> 
    <img id="blah1" src="#" alt="your image" /> 
</div> 

的JavaScript

function readURL(input) { 
    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 
     reader.onload = function (e) { 
      $('#blah') 
       .attr('src', e.target.result) 
       .width(150) 
       .height(200); 
     }; 
     reader.readAsDataURL(input.files[0]);   
    } 
    if (input.files && input.files[0]) { 
     var reader = new FileReader();  
     reader.onload = function (e) { 
      $('#blah1') 
       .attr('src', e.target.result) 
       .width(150) 
       .height(200); 
     }; 
     reader.readAsDataURL(input.files[0]);      
    } 
} 
+0

你將無法做到這一點。看到這個問題:http://stackoverflow.com/questions/1017224/dynamically-set-value-of-a-file-input – 2015-04-03 09:43:31

+0

@ArtyomNeustroev這不是問題 – 2015-04-03 10:09:07

回答

1

您可以嘗試通過您要使用的是$( '#嗒嗒' 來change.As img元素的id )爲這兩個函數調用,因此兩個時間相同的圖像正在顯示。您可以這樣做:

<script> 
     function readURL(input,x) { 
      if (input.files && input.files[0]) { 
       var reader = new FileReader(); 
       x = '#'+x; 
       reader.onload = function (e) { 
        $(x) 
         .attr('src', e.target.result) 
         .width(150) 
         .height(200); 
       }; 
       reader.readAsDataURL(input.files[0]); 
      } 
     } 
</script> 
<div class="person_pic"> 
    <label>Please upload your photo</label> 
    <input type='file' name="image" onchange="readURL(this,'blah');" /> 
    <img id="blah" src="#" alt="your image" /> 
</div> 
<div class="person_pic"> 
    <label>Please upload your family photo</label> 
    <input type='file' name="image" onchange="readURL(this,'blah1');" /> 
    <img id="blah1" src="#" alt="your image" /> 
</div> 
+0

非常感謝你 – 2015-04-03 10:37:17

+0

這個答案只看我看 – 2015-04-03 10:37:46

相關問題