简体   繁体   English

foreach检查图像是否存在

[英]foreach check if image exists

I need to make the foreach loop on the result return by the ajax. 我需要在ajax返回的结果上进行foreach循环。 While doing foreach I am checking against each record that image exist or not. 在执行foreach时,我正在对照每个记录检查图像是否存在。

Image Existence Code 图像存在代码

function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}

For each loop 对于每个循环

 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>';

When I console it only gives me the above string that has ul. 当我进行控制台操作时,它只会给我上面包含ul的字符串。 The string inside the imageExists does not concat. imageExists内部的字符串不连续。

That's because, even though $.each is synchronous, imageExists is not and therefore the concatenations happen too late. 这是因为,即使$.each是同步的, imageExists也并非如此,因此串联发生得太迟了。

What you can do is return Promise instances from the latter, and make use of Promise.all . 您可以做的是从后者返回Promise实例,并使用Promise.all

Demo : 演示

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM