仅使用一个按钮添加多图像

时间:2016-04-14 21:17:44

标签: jquery multi-upload

我实现了多图像上传并且工作正常。我的问题是我想用一个按钮实现它。单击时,将弹出浏览对话框并选择图像。我怎么能这样做?

var counter = 0;
$(document).ready(function() {
//  To add new input file 
$('[id^=add_more]').click(function() {
    $("#show" + this.id.replace(/\D/g, "")).append($("<div/>", {
        id: 'filediv'
    }).fadeIn('slow').append($("<input/>", {
        name: 'theImage',
        type: 'file',
        id: 'file'
    })));
});

$('body').on('change', '#file', function() {
    if (this.files && this.files[0]) {
        var ext = $( this).val().split('.').pop().toLowerCase();
        if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
            $('#file').val('');
            $('#file').remove();
            alert('Type Of File Is Not Valid!');
        }else{
            counter += 1; 
        $(this).before("<div id='abcd" + counter + "' class='abcd'><img id='previewimg" + counter + "' src=''/></div>");
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
        $(this).hide();
        $("#abcd" + counter).append($("<i/>", {
            class: 'fa fa-times',
            id: 'img',
            top:0,
            alt: 'delete'
        }).click(function() {
            $(this).parent().parent().remove();
        }));
        }

    }
});
//  Preview Img
function imageIsLoaded(e) {
    $('#previewimg' + counter).attr('src', e.target.result);
}
});

1 个答案:

答案 0 :(得分:0)

添加后,在最后一个输入上触发click()事件。

$('[id^=add_more]').click(function() {
    $("#show" + this.id.replace(/\D/g, "")).append($("<div/>", {
        id: 'filediv'
    }).fadeIn('slow').append($("<input/>", {
        name: 'theImage',
        type: 'file',
        id: 'file'
    })));
    $("#file").click();
});