如何检查每个块的图像,如果它是空的,则在里面加载图像。
我的尝试:
function showFile(e) {
var files = e.target.files;
var a = 1;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) continue;
var fr = new FileReader();
fr.onload = (function(theFile) {
return function(e) {
$('.tra').each( function() {
var $this = $(this);
if ( $this.find('img').length === 0 ) {
$this.append('<img src="'+e.target.result+'">');
} else {
alert("You can select only 5 images");
}
});
};
})(f);
fr.readAsDataURL(f);
}
}
document.getElementById('photo').addEventListener('change', showFile, false);
上传图片后,我想显示此图片:
HTML:
<div class="tra full_photo">
</div>
<div class="tra mini_photo">
<div class="tra block_mini_photo block_mini_photo2"></div>
<div class="tra block_mini_photo block_mini_photo3"></div>
<div class="tra block_mini_photo block_mini_photo4"></div>
<div class="tra block_mini_photo block_mini_photo5"></div>
</div>
<form>
<input type="file" name="photo[]" id="photo" class="upload_true" accept="image/jpeg,image/png,image/gif" multiple>
</form>
但是加载后,所有的块都被填满了 jsfiddle
答案 0 :(得分:2)
你这样做:
return function(e) {
var tra = $('.tra');
var one = false;
// test each single div
tra.each(function(){
if($(this).find('img').length <= 0 && !one){
$(this).append('<img src="'+e.target.result+'">');
one = true;
}
});
if(!one){
alert("You can select only 5 images");
}
};
答案 1 :(得分:0)
我的建议如下。查看演示 - https://fiddle.jshell.net/ermakovnikolay/sv7qy5qe/6/。
$('.tra').each( function() {
var $this = $(this);
if ( $this.find('img').length === 0 ) {
$this.append('<img src="'+e.target.result+'">');
} else {
alert("You can select only 5 images");
}
});