猿问

jquery 上傳前預覽

$(function(){
 $("#id").change(function(){  if (this.files && this.files[0]) {   var reader = new FileReader();
   
   reader.onload = function (e) {
    $('#pre').attr('src', e.target.result);
   }
   reader.readAsDataURL(this.files[0]);
  }
 });
});

以上我可以讓圖片能夠預覽這沒問題
但是當我有四個不同的上傳前預覽的表單時
這好像就會有問題..就是選擇好圖片後 img src不會改變
有把id和pre都改成不一樣的
但還是有問題
不會帶入路徑到img src
請問若有四個表單需要這個code
如何區隔開來?



蛊毒传说
浏览 505回答 1
1回答

拉丁的传说

可以用传参的方法<img style="width:110px; height:110px;" id="picture_1" src="" alt="form1"><input type="file" onchange="uploadPicturePre(this,'form1');"><img style="width:110px; height:110px;" id="picture_2" src="" alt="form2"><input type="file" onchange="uploadPicturePre(this,'form2');">//定义数据关系var picAll = {&nbsp; &nbsp; form1: { id: '#picture_1', type: 'form1', blob: null },&nbsp; &nbsp; form2: { id: '#picture_2', type: 'form2', blob: null },&nbsp; &nbsp; form3: { id: '#picture_3', type: 'form3', blob: null },&nbsp; &nbsp; form4: { id: '#picture_4', type: 'form4', blob: null }};//预览上传图片//pictureType的值为form1、form2等function uploadPicturePre(item, pictureType) {&nbsp; &nbsp; $(picAll[pictureType].id).attr('src', '').hide();&nbsp; &nbsp; picAll[pictureType].blob = null;&nbsp; &nbsp; var me = item;&nbsp; &nbsp; if (!me.files || !(new FileReader())) {&nbsp; &nbsp; &nbsp; &nbsp; $(me).val('').get(0).parentNode.nextSibling.value = '';&nbsp; &nbsp; &nbsp; &nbsp; alert('您的浏览器不支持files或FileReader对象');&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; if (me.files.length <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; $(me).val('').get(0).parentNode.nextSibling.value = '';&nbsp; &nbsp; &nbsp; &nbsp; alert('您未选择文件');&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; var file = me.files[0];&nbsp; &nbsp; if (!IsValidFileExtention(me.value, ["jpeg", "jpg", "png"])) {&nbsp; &nbsp; &nbsp; &nbsp; $(me).val('').get(0).parentNode.nextSibling.value = '';&nbsp; &nbsp; &nbsp; &nbsp; alert("文件格式不正确!");&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; var fileReader = new FileReader();&nbsp; &nbsp; fileReader.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; $(picAll[pictureType].id).attr('src', fileReader.result).show();&nbsp; &nbsp; &nbsp; &nbsp; $(picAll[pictureType].id).attr('data-original', fileReader.result).show();&nbsp; &nbsp; &nbsp; &nbsp; picAll[pictureType].blob = file;&nbsp; &nbsp; };&nbsp; &nbsp; fileReader.readAsDataURL(file);}思路大概是这样。。。点击查看代码 运行及效果截图如下:
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答