代码之家  ›  专栏  ›  技术社区  ›  Millhorn

使用“上载”按钮将多个图像上载到页面时出现问题。。。

  •  2
  • Millhorn  · 技术社区  · 10 年前

    我有一个 Fiddle here ...

    我已经完成了在上传按钮下方加载图像的功能,但是,如何将多个图像上传到同一页面?有三个地方我允许用户上传特定的图像。

    <div class="element-file" title="Do you want to add an image to the Accreditation Text?">
        <label class="title" style="font-weight: bold;">Add an image to the left of the Accreditation text<br>(Image will be resized to 100px by 100px)</label>
    
        <label class="medium" >
                <input type='file' onchange="readURL(this);" />
        </label>
            <p><strong>(Image will display below)</strong></p>
                <div style="max-width: 100px; height: auto; border:1px dashed black;">
                    <img id="accred_image" src="accred" alt="" />
                </div>
    </div>
    

    并将图像添加到此区域。。。

    <div class="element-file" title="Do you want to add an image to the Accreditation Text?">
        <label class="title" style="font-weight: bold;">Would you like to add a logo image?</label>
    
        <label class="medium" >
                <input type='file' onchange="readURL(this);" />
        </label>
            <p><strong>(Image will display below)</strong></p>
                    <div style="max-width: 140px; height: auto; border:1px dashed black;">
                        <img id="blah" src="" alt="" />
                    </div>
    </div>
    

    这是我的javascript,但当我上传图像时,它会在两个位置放置相同的图像。我以为这与我上传的类有关,但创建新类似乎一点帮助都没有。

    $("input").change(function(e) {
    
        for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
    
            var file = e.originalEvent.srcElement.files[i];
    
            var reader = new FileReader();
            reader.onloadend = function() {
                 $('#accred_image').attr('src', reader.result);
            }
            reader.readAsDataURL(file);        }
    });
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   MarianaAFSilva    10 年前

    您需要找到要更新的img。 试试看:

    $("input").change(function(e) {
    
        var elemIMG = $(this).parent().parent().find('img'); // find the img to update
    
        for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
    
            var file = e.originalEvent.srcElement.files[i];
    
            var reader = new FileReader();
            reader.onloadend = function() {
                  elemIMG.attr('src',reader.result); // update the img src
            }
            reader.readAsDataURL(file);        }
    });