【问题标题】:How to order concurrent google image searches in order of execution?如何按执行顺序排序并发谷歌图片搜索?
【发布时间】:2009-09-15 05:39:16
【问题描述】:

大家好,我不知道如何解决这个问题。我有一个传递 HTML img 元素数组的函数。它循环遍历这些图像,使用空白的“无图像”缩略图检查图像的 SRC 属性。然后它使用 img tags ALT 属性作为查询执行图像搜索。然后搜索的回调函数将 Img SRC 替换为第一个图像结果。

我在将正确的图像与相应的搜索回调匹配时遇到问题。现在我只是创建数组并将返回的搜索与图像索引匹配。由于多个搜索同时运行,根据图像的大小或网络延迟,它们可能会无序地触发回调并混淆图像。

我需要一种方法,让我将单个搜索与 html 元素配对。这可以使用一个 searchController 和多个 imageSearch 对象吗?

下面是我正在使用的函数示例

google.load('search', '1');

function googleFillBlanks(jqueryImages){

  //namePairs holds the images matching alt text and attachedCount is used for matching up once the call back is fired
  var attachedCount = 0;
  var namePairs = [];

  function searchComplete(searcher){
    if (searcher.results && searcher.results.length > 0) {
       var results = searcher.results;
       var result = results[0];
       $("img[alt='"+namePairs[attachedCount]+"'] ").attr('src', result.tbUrl);
       //jqueryImages.get(0).attr('src', result.tbUrl);
       attachedCount++;
    }
  }

   var imageSearch = new google.search.ImageSearch();

    //restrict image size
    imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                               google.search.ImageSearch.IMAGESIZE_SMALL);

    imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);

  jqueryImages.each(function(){
    if($(this).attr('src').substr(-12,8) == 'no_image')
    { 
      namePairs.push($(this).attr('alt'));
      imageSearch.execute($(this).attr('alt'));
    }
  });
}

【问题讨论】:

    标签: jquery google-api google-search-api


    【解决方案1】:

    这就是我最终做的事情,包括任何有兴趣的人和自我提醒

    google.load('search','1');
    function checkImages(){
    
     // Here is the closure!
     var myClosure = function(img){return function(){
      if(this.results&&this.results.length>0){
       var result = this.results[0];
       img.src = result.tbUrl;
       img.alt = result.titleNoFormatting;
      }
     }};
    
     var imgs = document.getElementsByTagName('img');
     for(var i=0;i<imgs.length;i++){
      var img=imgs[i];
      if(img.src.match(/no_image.{4}/)){
       var is = new google.search.ImageSearch();
       is.setSearchCompleteCallback(is, myClosure(img));
       is.execute(img.alt);
      }
     }
    }
    google.setOnLoadCallback(checkImages);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多