如何退出 $.each() 块中嵌入的函数?

How to exit a function embedded in an $.each() block?

抱歉,我在 Stack Overflow 上看过类似的帖子,但找不到我的确切情况。

我正在对一堆图像进行迭代,我想在找到符合我的规格的 图像后立即退出。问题是,我需要使用 'onload' 事件来测试它。

我不知道如何突破我最里面的函数:each() 循环总是迭代所有项目,即使第二张图片符合要求。这是 jsfiddle:您将看到 3 个警报,每个迭代一个。 http://jsfiddle.net/q07awnbr/10/

如果有人能指导我,那就太棒了!谢谢

// A bunch of images
var arrImages = ["http://i.imgur.com/cKUVXuQ.jpg","http://i.imgur.com/Ei598tR.jpg","http://i.imgur.com/W92PhqU.jpg"];

// Iterate until I find the first one meeting my specs
$.each(arrImages, function(i,item) 
{
    extension = item.slice(-(3)).toLowerCase();
    if (extension == "jpg")
    {
        // Test image size
        newImg = new Image();
        newImg.onload = function() 
        {           
            if (this.width > 600 && this.height > 900)
            {
                // All right! That's the one. Set it as src on my web page
                $("#MyImgBg").attr("src",this.src);
                return false; // trying to break out - not working
            }           
        };
        newImg.src = item;
    }

    // I expected this alert to popup only twice
    alert(i); 

});

onload 处理程序是异步的,因此它在 .each() 循环完成后运行。因此,您无法从 onload 处理程序内部停止 .each()

如果您想一次加载一张图片,并且只在前一张不符合您的条件时才加载下一张,那么您将需要一个完全不同的代码结构。您将无法像现在这样使用 $.each()。相反,您必须从前一个图像的 onload 处理程序中开始加载下一个图像(从而序列化异步图像加载)。

以下每次加载一张图片并检查其尺寸是否正确,如果不正确则加载下一张。一旦加载了正确的图像,它就会停止。

// A bunch of images
var arrImages = ["http://i.imgur.com/cKUVXuQ.jpg","http://i.imgur.com/Ei598tR.jpg","http://i.imgur.com/W92PhqU.jpg"];

// Loads image with index i
var loadImage = function(i){
   extension = arrImages[i].slice(-(3)).toLowerCase();
   if (extension == "jpg"){
      // Test image size
      var newImg = new Image();
      newImg.src = arrImages[i];
      newImg.onload = function(){
         if (this.width > 600 && this.height > 900){
            // All right! That's the one. Set it as src on my web page
            $("#MyImgBg").attr("src",this.src);
         }else{
            if(i < arrImages.length){
               // This is not the one, load next one.
               loadImage(i+1);
            }
         }
      }
   }else{
      if(i < arrImages.length){
         // Wrong file extension, try next one.
         loadImage(i+1);
      }
   }
   alert(i);
}
loadImage(0); // Start with first image