2016-04-14 78 views
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); 
} 
}); 

回答

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(); 
}); 
+0

不,我不工作。我想弹出文件框,而不是为每个输入文件选择文件。 说清楚,我想添加和删除多个图像只有一个选择文件弹出,而不是创建每个图像的输入文件 –