大家好,我不知道如何解决这个问题。我有一个传递 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'));
}
});
}