2009-09-15 58 views
1

大家好,我不知道如何解決這個問題。我有一個函數傳遞了一個HTML img元素的數組。它循環瀏覽這些圖像,使用空白的「無圖像」縮略圖檢查圖像的SRC屬性。然後使用img標籤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')); 
    } 
    }); 
} 

回答

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);