jQuery在更改文件输入时更改多个图像src

时间:2017-05-17 11:03:25

标签: javascript jquery image file-upload src

我试图将默认文件上传的样式更改为基于的预览。 在更改输入字段时,我想更新预览图像的src。这是工作,但只是第一种类型的文件输入。如果我想添加上传输入,我想要灵活。你能帮我找到我错误的想法吗?

HTML

<div class="file-uploader">

<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-1" style="display:none;" />
<img class="preview-1" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>

<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-2" style="display:none;" />
<img class="preview-2" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>

</div>

脚本

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();            
            reader.onload = function (e) {
                $('.file-uploader .preview-'+num_id).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    var num_id = $(".file-uploader input[type='file']").attr('class').match(/\d+/); 
    $(".file-uploader .upload-field-"+num_id).change(function(){
        readURL(this);
    });

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();            
            reader.onload = function (e) {
                var num = $(input).attr('class').split('-')[2];
                $('.file-uploader .preview-'+num).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    } 
    
    $("[class^=upload-field-]").change(function(){
        readURL(this);
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-uploader">

<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-1" style="display:none;" />
<img class="preview-1" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>

<label name="upload-label" class="upload-img-btn">
<input type="file" class="upload-field-2" style="display:none;" />
<img class="preview-2" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Torchlight_viewmag_plus.png" style="width:150px!important;" />
</label>

</div>
&#13;
&#13;
&#13;

请检查代码可能会帮助您

由于