0

Google画像検索APIを使用する次のコードがあります:

google.load('search', '1');   
    function searchComplete(searcher) {
      // Check that we got results
      if (searcher.results && searcher.results.length > 0) {
        // Grab our content div, clear it.
        var contentDiv = document.getElementById('contentimg');
        contentDiv.innerHTML = '';

        // Loop through our results, printing them to the page.
        var results = searcher.results;
        for (var i = 1; i < results.length; i++) {
          // For each result write it's title and 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);

問題は、3 つの画像結果が得られることです。ループを中断して、3 つの画像ではなく最初の画像のみを表示するにはどうすればよいですか? 変更for (var i = 1; i < results.length; i++)するfor (var i = 3; i < results.length; i++)と画像が 1 つだけ表示されますが、表示される画像は 3 番目の画像であり、1 番目の画像を表示する必要があります :) アドバイスをお願いします

4

3 に答える 3

5

for ループをまったく使用しないでください。iのすべてのインスタンスを 0に置き換えるだけです。

google.load('search', '1');   
    function searchComplete(searcher) {
      // Check that we got results
      if (searcher.results && searcher.results.length > 0) {
        // Grab our content div, clear it.
        var contentDiv = document.getElementById('contentimg');
        contentDiv.innerHTML = '';

        var result = searcher.results[0];

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

0 は最初に返された項目を意味します (プログラミングのほとんどすべての数列は 0 から始まります!)、他のすべての結果は無視されます。

于 2012-08-30T13:33:39.510 に答える
0

使用してbreak statementください。画像が見つかるとループが終了するため、最初の画像のみが表示されます。

      for (var i = 1; i < results.length; i++) {
      // For each result write it's title and 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);
       //Berore the end of the loop
      if(i==1)
      {
      break;
      }
   }
于 2012-08-30T13:35:11.000 に答える
0

要素が 1 つだけ必要な場合は、for ループは必要ありません。配列の最初の要素にアクセスするには、

result = results[0];

配列はゼロベースです。したがって、3 つの画像が含まれている場合、画像には results[0]、results[1]、results[2] という名前が付けられます。

于 2012-08-30T13:37:25.337 に答える