我正在尝试在我的网站上的div中放置Google新闻搜索。我目前正在使用谷歌提供的脚本,但我是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>
答案 0 :(得分: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/
这里没有很多东西可以搞乱。我想你可能有一个语法错误,并没有检查控制台是否有错误。