我有一个画廊,在页面中点击加号和减号来添加和删除画廊项目,然后添加文件添加到新添加的项目的输入。我如何获得jQuery的.each函数动态元素的.on('更改')功能
我已经创建了一个文件读取器来获取文件的url,但它只能在该页面上的第一个元素上工作,在这之后添加的任何内容都不会受到影响。
这里是我的JS:
$('#gallery .gallery-item .file_upload').each(function() {
var $this = $(this);
//$('body').on('click', 'input', function() {
$this.on('change', 'input', function(evt){
var files = evt.target.files;
var file = files[0];
console.log(files[0]);
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
console.log(e.target.result);
};
})(file);
reader.readAsDataURL(file);
});
});
追加画廊项功能:
$('#gallery')
.on('cocoon:before-insert', function(e,image_field) {
image_field.insertAfter($(this).next());
})
.on('cocoon:after-remove', function(e, image_field) {
$(this).data('remove-timeout', 1000);
image_field.fadeOut('slow');
});
$('.gallery-item').each(function() {
$(this).next('a.add_fields').appendTo(this);
$(this).next('input').appendTo(this);
});
HTML:
<div class="image-field">
<div class="file_upload">
<input class="image_file" id="gallery_files" name="book[gallery_attributes][images_attributes][1412768497650][file]" type="file">
</div>
</div>
谁能告诉我为什么。每个功能将无法正常工作这个.on函数用于附加的新项目。我认为这是最重要的功能,显然不适用于这里,而不是下面的其他功能。
工作是的,它是委托的顺序,所以它从父div的id开始,而.on基本上贯穿'.gallery-item .file_upload input'中的每个子节点,然后运行'.on( '变化')'。很感谢Anthony的解释。 :) – 2014-10-08 12:08:30