0

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

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);
}
});
4

1 回答 1

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();
});
于 2016-04-14T21:58:40.813 回答