2017-01-06 28 views
0

這是jQuery中的單圖上傳預覽功能。我想單獨更改多個功能(如每個框)以上傳照片,您可以在下面的html腳本中看到這些照片。如何讓jquery多圖預覽

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> 
<script> 

function imagepreview(input){ 
    if(input.files && input.files[0]){ 
     var filerd = new FileReader(); 
     filerd.onload=function(e){ 
      $('#imgpreview').attr('src', e.target.result); 
     }; 
     filerd.readAsDataURL(input.files[0]); 
    } 
    } 

</script> 
<style> 
body{ 
font-family:arial; 
} 
.wrap{ 
border:0px solid; 
width:40%; 
margin:10px auto; 
} 

table, th, td { 
    border: 1px solid black; 
    border-collapse: collapse; 
    text-align:center; 
    padding:10px; 
} 
#idupload{ 
    display:none; 
} 
.input-label{ 
    background-color:#009688; 
    color:#fff; 
    padding:5px 15px; 
} 
</style> 
</head> 
<body> 

<div class="wrap"> 
<table> 
    <tr> 
    <th><img id="imgpreview" src="" width="100" height="100"></th> 
    <th><img id="imgpreview" src="" width="100" height="100"></th> 
    <th><img id="imgpreview" src="" width="100" height="100"></th> 
    </tr> 
    <tr> 
    <td><label for="idupload" class="input-label"><i class="fa fa-arrow-up"></i>upload</label><input type="file" id="idupload" onchange="imagepreview(this);" /></td> 
    <td><label for="idupload" class="input-label"><i class="fa fa-arrow-up"></i>upload</label><input type="file" id="idupload" onchange="imagepreview(this);" /></td> 
    <td><label for="idupload" class="input-label"><i class="fa fa-arrow-up"></i>upload</label><input type="file" id="idupload" onchange="imagepreview(this);" /></td> 
    </tr> 
</table> 
</div> 

</body> 
</html> 

回答

0

問題是你有重複的ID,並且功能imagepreview()一直更新與圖片上傳相同的ID。要解決此問題,請爲每個圖像預覽指定一個唯一的ID,並在文件上傳框中放置相同的對應標識,以便唯一的文件上傳框將更新唯一的圖像預覽。

這是一個演示。我給預覽和上傳一個唯一的ID,然後在imagepreview()我解析上傳框ID的ID,並將其添加到頁面上更新的圖像預覽的ID。 http://codepen.io/anon/pen/apOyZB

+0

@Farooq你打賭! –

+0

我可以加你fb嗎? – Farooq

+0

我想實現相同功能刪除圖像事件? – Farooq