【问题标题】:jQuery change multiple image src on change of file inputjQuery在更改文件输入时更改多个图像src
【发布时间】:2017-10-16 19:24:11
【问题描述】:

我正在尝试将我的默认文件上传的样式更改为基于的预览。 在更改输入字段时,我想更新预览图像的 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);
    });

【问题讨论】:

  • 您需要将 'num_id' 传递给 readURL()。应该是 readURL(this, num_id);
  • 我以前也试过这个,但没有改变任何东西。 :(
  • $('.file-uploader .preview-'+num_id) - 此行不会获取 num_id,因此您需要传递该变量。另外,尝试使用 console.log() 进行调试并检查流程。

标签: javascript jquery image file-upload src


【解决方案1】:

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>

请检查代码可能对您有所帮助

谢谢

【讨论】:

  • 非常感谢您的帮助!最好的问候卢卡斯
猜你喜欢
  • 2014-09-10
  • 2014-09-27
  • 2020-07-30
  • 1970-01-01
  • 2023-03-27
  • 2011-06-26
  • 2012-08-07
  • 2018-10-25
相关资源
最近更新 更多