预览上传的照片以进行动态输入



图像是用于选择照片的按钮。 选择图像后,将查看所选图像并生成新图像按钮。我只能使用 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);
});

这是演示

尝试使用这个更新的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 for the same

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

最新更新