2016-12-16 54 views
2

我有一些問題,我試圖解決自己。但我沒有。我創建的腳本可以一次上傳多張圖片。我第一次得到一個輸入文件字段,並且如果有人爲上傳字段添加了照片,我寫了一個JavaScript,然後自動生成新的上傳字段。這是第一次運作良好。它成功地生成了新的上傳字段。但它沒有第二次產生。我假設你有一個關於bootstrap的知識。動態生成輸入類型=「文件」元素多次上傳

這裏是我的HTML代碼

<input type ="file" class ="fileup 1" id ="file1"> 
<label for ="file1" id ="lbl_upload"> 
<span class ="glyphicon glyphicon-plus-sign"></span></label> 
<div class ="photos"> </div> 

這裏我的JavaScript代碼

var count = 1; 
$("#file1" + count).on('change', '.fileup', function() { 
    var files, imagetype, matches; 
    files = this.files[0]; 
    imagetype = files.type; 
    matches = ["image/jpeg"]; 
    var str = "#img_nxt" + count; 
    if (!(imagetype == matches[0])) { 
     alert("Wrong format"); 
    } else { 
     $('#lbl_upload').remove(); 
     $('.photos').append("<img id='img_nxt" + count + "' width ='100' height ='100'> "); 
     //create a new input file element 
     count++; 
     $('.photos').append("<input type =\"file\" class =\"fileup " + count + "\" id =\"file" + count + "\"><label for =\"file" + count + "\" id =\"lbl_upload\"><span class =\"glyphicon glyphicon-plus-sign\"></span></label>"); 
     //show picture in image element 
     var reader = new FileReader(); 
     reader.onload = function(e) { 
      $(str).attr("src", e.target.result); 
     } 
     reader.readAsDataURL(files); 
     return true; 
    } 
}); 

這裏是我的CSS

[class*="fileup"]{ 
position:fixed; 
top:5000px; 
} 

我哪裏錯了?感謝您花時間爲我制定解決方案。

回答

1

目前使用的是所謂的「直接「綁定,它只會綁定到代碼在進行事件綁定調用時存在於頁面上的元素。

在動態生成元素時,您需要使用委託事件方法Event Delegation。由於您已經使用file輸入控件的普通類fileup將代碼改爲

$('.photos').on('change', '.fileup', function() { 
    //Your code 
}); 
1

這是因爲點擊事件沒有與動態添加的元素相關聯。在這種情況下,您應該使用event delegation

事件代理允許我們將一個事件監聽器附加到父元素,該父元素將觸發所有與選擇器匹配的後代,無論這些後代是現在存在還是將來都會添加。

此外,作爲ID與固定開始與模式動態生成的,你可以使用屬性開始選擇同時使用事件委託綁定的事件:

$('.photos').on('change','[id^=file]',function(){ 
相關問題