我想写一个网页,可以动态生成从谷歌搜索中获取的图像。这些图片的搜索条件不同,所以我需要执行几次谷歌搜索,而我发现它非常困难。我尝试从谷歌提供的源代码修改这些代码,但它只能执行一次搜索:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
var keyword="sexy";
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src=result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
//clear search
imageSearch.clearResults();
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
imageSearch.execute(keyword);
}
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<button value="hi" onClick="hi">hi</button>
<div id="content">Loading...</div>
</body>
</html>
程序只能在 OnLoad 方法中执行搜索。实际上,我尝试通过将 google.setOnLoadCallback(OnLoad) 放入 hi() 函数中多次调用它,但它没有用。希望有人可以帮助我解决这些问题..