javascript - foreach 检查图像是否存在
问题描述
我需要在ajax返回的结果上进行foreach循环。在执行 foreach 时,我正在检查每个记录是否存在图像。
图像存在代码
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
对于每个循环
hotelImagesText = '<ul class="gallery list-unstyled cS-hidden" id="image-gallery">';
$.each(hotelImagesArr, (index, item) => {
imageExists(item, function(exists) {
if (exists) {
hotelImagesText += '<li data-thumb="'+hotelImagesArr[index]+'">
<img src="'+hotelImagesArr[index]+'"></li>';
}
});
});
hotelImagesText += '</ul>';
当我控制台它只给我上面有 ul 的字符串。imageExists 中的字符串没有连接。
解决方案
那是因为,即使$.each
是同步的,imageExists
也不是,因此连接发生得太晚了。
您可以做的是Promise
从后者返回实例,并使用Promise.all
.
演示:
function imageExists(url) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = url;
});
}
const hotelImagesArr = [
'https://www.sample-videos.com/img/Sample-jpg-image-50kb.jpg',
'https://www.sample-videos.com/img/Sample-jpg-image-100kb.jpg',
'https://stackoverflow.com/idonotexist.jpg'
];
let hotelImagesText = '<ul class="gallery list-unstyled cS-hidden" id="image-gallery">';
const checks = hotelImagesArr.map(url => imageExists(url));
Promise.all(checks).then(checksResults => {
for (let i in checksResults) {
if (checksResults[i]) {
hotelImagesText += `<li data-thumb="${hotelImagesArr[i]}"><img src="${hotelImagesArr[i]}"></li>`;
}
}
hotelImagesText += '</ul>';
console.log(hotelImagesText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
推荐阅读
- flutter - Flutter:AnimatedContainer的基于child宽度的动画
- windows-7 - Win 7 ESU - 2 月以后更新 SCCM 部署问题
- android - Firebase 数据库无法更新
- java - 如何使用 @ElementCollection 进行设置
映射? - image - 使用PowerShell查找和复制多张图片
- android - 有没有一种方法可以设置和合并而无需为仅 1 个值创建地图
- terraform - 跨 terraform 工作区共享 Google Cloud Platform 项目
- flutter - Flutter:如何禁用和启用播放/暂停耀斑动画?
- c# - 将两行合二为一?
- python - 分配职位