我试图将默认文件上传的样式更改为基于。在更改输入字段时,我希望更新预览图像的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);
});发布于 2017-05-17 12:00:15
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);
});<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>
请检查一下代码可能会帮你解决问题。
谢谢
https://stackoverflow.com/questions/44023028
复制相似问题