1

我想写一个网页,可以动态生成从谷歌搜索中获取的图像。这些图片的搜索条件不同,所以我需要执行几次谷歌搜索,而我发现它非常困难。我尝试从谷歌提供的源代码修改这些代码,但它只能执行一次搜索:

    <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() 函数中多次调用它,但它没有用。希望有人可以帮助我解决这些问题..

4

2 回答 2

0

hi功能对我来说没有多大意义:

function hi(){
    keyword="usa";
    alert('hi');
    google.setOnLoadCallback(OnLoad);
    imageSearch.execute(keyword);
}

因为onLoadCallbak已经设置,并且中执行了搜索OnLoad。这在搜索库加载时调用。这只发生一次,在页面加载后的某个时刻。

您需要做hi的事情与您正在做的事情相同OnLoad

// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();

// set a DIFFERENT callback (if different handling require)
imageSearch.setSearchCompleteCallback(this, searchComplete, null);

// set "keyword" to what your next search should be for
imageSearch.execute(keyword);
于 2014-02-03T19:20:33.407 回答
0

更改<button value="hi" onClick="hi">hi</button>

<button value="hi" onClick="hi()">hi</button>

于 2013-05-23T10:08:37.087 回答