0

我正在尝试在我的网站上的 div 中放置谷歌新闻搜索。我目前正在使用谷歌提供的脚本,但我是 Ajax/JavaScript 的新手。我能够显示来自谷歌新闻的最新故事,但不知道如何在 div 中显示它,更不用说使用 CSS 操作样式了。下面是我正在使用的代码。任何帮助将不胜感激!

<script type="text/javascript">

    google.load('search', '1');

    var newsSearch;

    function searchComplete() {

      // Check that we got results
      document.getElementById('averagecontainer').innerHTML = '';
      if (newsSearch.results && newsSearch.results.length > 0) {
        for (var i = 0; i < newsSearch.results.length; i++) {

          // Create HTML elements for search results
          var p = document.createElement('p');
          var a = document.createElement('a');
          a.href = newsSearch.results[i].url;
          a.innerHTML = newsSearch.results[i].title;

          // Append search results to the HTML nodes
          p.appendChild(a);
          document.body.appendChild(p);
        }
      }
    }

    function onLoad() {

      // Create a News Search instance.
      newsSearch = new google.search.NewsSearch();

      // Set searchComplete as the callback function when a search is 
      // complete.  The newsSearch object will have results in it.
      newsSearch.setSearchCompleteCallback(this, searchComplete, null);

      // Specify search quer(ies)
      newsSearch.execute('Barack Obama');

      // Include the required Google branding
      google.search.Search.getBranding('branding');
    }

    // Set a callback to call your code when the page loads
    google.setOnLoadCallback(onLoad);

    </script>
4

1 回答 1

0

如果我理解正确,这就是您需要的:

创建<div>并给它一个ID:

<div id="your-div">HERE BE NEWS</div>

然后像这样修改 searchComplete 函数:

function searchComplete() {

  var container = document.getElementById('your-div');
  container.innerHTML = '';

  if (newsSearch.results && newsSearch.results.length > 0) {
    for (var i = 0; i < newsSearch.results.length; i++) {

      // Create HTML elements for search results
      var p = document.createElement('p');
      var a = document.createElement('a');
      a.href = newsSearch.results[i].url;
      a.innerHTML = newsSearch.results[i].title;

      // Append search results to the HTML nodes
      p.appendChild(a);
      container.appendChild(p);
    }
  }
}

至于样式操作,您可以通过 css 中的给定 ID 匹配元素。例如像这样:

#your-div a {
    font-weight: bold;
}

编辑:

为了向您展示这是有效的,我创建了一个 jsfiddle:http: //jsfiddle.net/enjkG/

你可以在这里搞砸的事情并不多。我认为您可能有语法错误并且没有检查控制台是否有错误。

于 2013-04-02T20:14:15.670 回答