【问题标题】:Only append document if image is valid using jquery如果图像有效,则仅使用 jquery 附加文档
【发布时间】:2022-01-05 18:15:19
【问题描述】:

我有一组需要添加到文档中的图像 url(如下所示)。有些网址不包含图片。如何检查?

picUrls = ["https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg","http://www.fakeurl.io/fakeimage1.jpeg","https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg"]

我正在使用 jquery 并尝试了 .load & .error

for(let i = 0; i < picUrls.length; i++) {
    const picUrl = picUrls[i];

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
      src: picUrl
    });
    
    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {
    
      //image loaded:
      //your code here to insert image into page
      $('#content-container').append(imgPreload);
    
    } else {
      //go fetch the image:
      $(imgPreload).load(function (response, status, xhr) {
        if (status == 'error') {
    
          //image could not be loaded:
          console.log('error');
        } else {
    
          //image loaded:
          //your code here to insert image into page
          $('#content-container').append(imgPreload);
    
        }
      });

【问题讨论】:

    标签: javascript html jquery ajax


    【解决方案1】:

    您可以创建一个帮助函数,该函数返回一个图像是否是有效图像的承诺

          const picUrls = [
            'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/048.jpg',
            'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18166-shivling-whatsapp-image-and-dp.jpg',
            'http://www.fakeurl.io/fakeimage1.jpeg',
            'https://s3-us-west-1.amazonaws.com/codesmith-precourse-images/18416-navratri-image-for-whatsapp-and-facebook.jpg',
          ];
    
          const getOnlyValidImage = src =>
            new Promise((resolve, reject) => {
              const img = new Image();
              img.src = src;
              img.onload = () => resolve(img);
              img.onerror = () => resolve(null);
            });
    
          const preloadImages = async () => {
            for (let i = 0; i < picUrls.length; i++) {
              const picUrl = picUrls[i];
              const image = await getOnlyValidImage(picUrl)
              if (image) {
                $('#content-container').append(image);
              }
            }
          };
    
          preloadImages();
    

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 2015-01-22
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 2011-09-14
      • 2017-11-12
      相关资源
      最近更新 更多