Pregunta

Hola a todos, no estoy seguro de cómo abordar este problema. Tengo una función que pasa una matriz de elementos img HTML. Recorre estas imágenes revisando el atributo SRC para imágenes usando un espacio en blanco "no hay imagen". miniatura. Luego ejecuta una búsqueda de imágenes usando el atributo img tags ALT como la consulta. La función de devolución de llamada en la búsqueda reemplaza el Img SRC con el primer resultado de la imagen.

Tengo problemas para hacer coincidir la imagen correcta con la devolución de llamada de búsqueda correspondiente. En este momento solo estoy creando matrices y haciendo coincidir la búsqueda devuelta con un índice para las imágenes. Dado que las búsquedas múltiples se ejecutan simultáneamente, según el tamaño de la imagen o la latencia de la red, pueden volver a activar la llamada fuera de servicio y mezclar las imágenes.

Necesito un enfoque que me permita emparejar búsquedas individuales con elementos html. ¿Sería posible esto usando un SearchController y múltiples objetos imageSearch?

A continuación se muestra un ejemplo de la función que estoy 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'));
    }
  });
}
¿Fue útil?

Solución

esto es lo que terminé haciendo encapsular a cualquiera que esté interesado y para recordarse a sí mismo

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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top