为了账号安全,请及时绑定邮箱和手机立即绑定

jquery 上傳前預覽

jquery 上傳前預覽

蛊毒传说 2018-09-14 14:13:52
$(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如何區隔開來?
查看完整描述

1 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

可以用传参的方法

<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 = {

    form1: { id: '#picture_1', type: 'form1', blob: null },

    form2: { id: '#picture_2', type: 'form2', blob: null },

    form3: { id: '#picture_3', type: 'form3', blob: null },

    form4: { id: '#picture_4', type: 'form4', blob: null }

};


//预览上传图片

//pictureType的值为form1、form2等

function uploadPicturePre(item, pictureType) {

    $(picAll[pictureType].id).attr('src', '').hide();

    picAll[pictureType].blob = null;


    var me = item;


    if (!me.files || !(new FileReader())) {

        $(me).val('').get(0).parentNode.nextSibling.value = '';

        alert('您的浏览器不支持files或FileReader对象');

        return false;

    }


    if (me.files.length <= 0) {

        $(me).val('').get(0).parentNode.nextSibling.value = '';

        alert('您未选择文件');

        return false;

    }


    var file = me.files[0];


    if (!IsValidFileExtention(me.value, ["jpeg", "jpg", "png"])) {

        $(me).val('').get(0).parentNode.nextSibling.value = '';

        alert("文件格式不正确!");

        return false;

    }


    var fileReader = new FileReader();

    fileReader.onload = function () {

        $(picAll[pictureType].id).attr('src', fileReader.result).show();

        $(picAll[pictureType].id).attr('data-original', fileReader.result).show();

        picAll[pictureType].blob = file;

    };


    fileReader.readAsDataURL(file);


}

思路大概是这样。。。

点击查看代码 运行及效果
截图如下:

https://img1.sycdn.imooc.com//5bd2c5ef0001c5f005820119.jpg

查看完整回答
反对 回复 2018-10-26
  • 1 回答
  • 0 关注
  • 504 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号