2016-04-14 79 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

不,我不工作。我想彈出文件框,而不是爲每個輸入文件選擇文件。 說清楚,我想添加和刪除多個圖像只有一個選擇文件彈出,而不是創建每個圖像的輸入文件 –