Pergunta

Oi tudo Estou não tenho certeza como abordar este problema. Eu tenho uma função que é passada uma série de elementos HTML img. Ele percorre essas imagens verificando o atributo SRC para imagens usando um espaço em branco "sem imagem" polegar prego. Em seguida, ele executa uma pesquisa de imagens usando o atributo ALT tags img como a consulta. A função de retorno na busca, em seguida, substitui o img src com o primeiro resultado da imagem.

Estou tendo problemas correspondentes a imagem correta com o retorno de chamada de pesquisa correspondente. Agora eu estou apenas criando matrizes e combinando a pesquisa devolveu com um índice para as imagens. Desde as várias pesquisas executadas simultaneamente, dependendo do tamanho da imagem ou rede latência que pode disparar a chamada de volta fora de ordem e misturar as imagens.

Eu preciso de uma abordagem que me permite emparelhar pesquisas individuais com elementos html. Será que isso é possível usando um searchController e imageSearch vários objetos?

A seguir é um exemplo da função que estou usando

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'));
    }
  });
}
Foi útil?

Solução

isto é o que eu acabei fazendo EnCase qualquer um está interessado e para a auto lembrete

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top