【问题标题】:preview uploaded photo for dynamic inputs预览上传的照片以进行动态输入
【发布时间】:2017-05-19 04:49:17
【问题描述】:

图像作为选择照片的按钮。选择图像后,将查看所选图像并生成新图像按钮。我只能使用 ID 对 1 个参数进行此操作。如何处理多个文件?

document.getElementById('imgInp').onclick = function() {
    document.getElementById('fileinpt').click();
};

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#imgInp').attr('src', e.target.result);
            $('.imgpc').after('<div class="col-sm-4 col-xs-6 imgpc"><div class="imagepreview"><span></span><img id="imgInp" src="images/add-photo.png" alt="Add more photo" /><input type="file" id="fileinpt" class="hidden"></div></div>');
        }

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

$("#fileinpt").change(function(){
    readURL(this);
});

这里是DEMO

【问题讨论】:

  • 这个问题是测验的一部分吗?
  • 我不这么认为。请检查我的演示。 @karthick
  • 使用 css 类选择器收集所有输入,您可以对其进行迭代。例如。 $('.imgpc input[type="hidden"]).attr('id')

标签: javascript jquery


【解决方案1】:

试试这个更新的 jquery

$(document).off('click', '#imgInp').on('click', '#imgInp', function (e) {
        $('#fileinpt').click();
});

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#imgInp').attr('src', e.target.result);                
            $('#imgInp').attr("id", "newimgInp");            

            $('.imgpc').append('<div class="imagepreview"><span></span><img id="imgInp" src="images/add-photo.png" alt="Add more photo" /></div>');
        }

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

$("#fileinpt").change(function(){
    readURL(this);
});

同样的jsfiddle

https://jsfiddle.net/jshp6zst/3/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2014-01-20
    • 2023-03-28
    • 2023-03-14
    相关资源
    最近更新 更多