我在页面中有一个画廊,您可以在其中单击加号和减号来添加和删除画廊项目,然后将文件添加到新附加项目的输入中。
我创建了一个文件读取器来获取文件 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>
谁能告诉我为什么 .each 函数不能与 .on 函数一起用于附加的新项目。我认为这是最上面的功能,显然在这里不起作用,而不是下面的其他功能。
最佳答案
您已经正确地确定需要使用事件委托(delegate),因为您已在页面上动态添加了元素。问题在于,事件委托(delegate)作用于代码运行时存在的元素,并且您使用 .each()
循环来迭代您期望的集合包含动态添加的元素(不会,因为它们当前不存在)。
本质上,问题出在初始选择器$('#gallery .gallery-item .file_upload')
。
该选择器的 .gallery-item .file_upload
部分是标识事件委托(delegate)的动态元素的一部分,因此您需要使用更像这样的内容:
$('#gallery').on('change', '.gallery-item .file_upload input', function(e) {
// your code here
});
我删除了对 .each()
的调用,因为它是多余的; .on()
已经迭代了一组匹配的元素,并且您的 $('#gallery')
选择器无论如何都应该只匹配单个元素。
注意:您在选择器中使用了 .gallery-item
,但您提供的 HTML 中只有一个 image-field
类。这可能是也可能不是问题,具体取决于页面的具体外观,因为您没有提供我不得不猜测的信息。
关于javascript - 如何让 jquery .each 函数与动态元素的 .on ('change' ) 函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26256282/