动态生成输入类型=“文件”元素多次上传
问题描述:
我有一些问题,我试图解决自己。但我没有。我创建的脚本可以一次上传多张图片。我第一次得到一个输入文件字段,并且如果有人为上传字段添加了照片,我写了一个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;
}
我哪里错了?感谢您花时间为我制定解决方案。
答
目前使用的是所谓的“直接“绑定,它只会绑定到代码在进行事件绑定调用时存在于页面上的元素。
在动态生成元素时,您需要使用委托事件方法Event Delegation。由于您已经使用file
输入控件的普通类fileup
。 将代码改为,
$('.photos').on('change', '.fileup', function() {
//Your code
});
答
这是因为点击事件没有与动态添加的元素相关联。在这种情况下,您应该使用event delegation。
事件代理允许我们将一个事件监听器附加到父元素,该父元素将触发所有与选择器匹配的后代,无论这些后代是现在存在还是将来都会添加。
此外,作为ID与固定开始与模式动态生成的,你可以使用属性开始选择同时使用事件委托绑定的事件:
$('.photos').on('change','[id^=file]',function(){