我想知道如何在下面提到的代码中添加错误检查...我的意思是如何检查此代码是否返回空?如果这返回空,那么我会给出一条消息“Not Found”.. 我该怎么办?
google.load('search', '1');
var blogSearch;
function searchComplete() {
// Check that we got results
document.getElementById('content').innerHTML = '';
if (blogSearch.results && blogSearch.results.length > 0) {
for (var i = 0; i < blogSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = blogSearch.results[i].postUrl;
a.innerHTML = blogSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
document.body.appendChild(p);
}
}
}
function onLoad() {
// Create a BlogSearch instance.
blogSearch = new google.search.BlogSearch();
// Set searchComplete as the callback function when a search is complete. The
// blogSearch object will have results in it.
blogSearch.setSearchCompleteCallback(this, searchComplete, null);
// Set a site restriction
blogSearch.setSiteRestriction('blogspot.com');
// Execute search query
blogSearch.execute('1974 Chevrolet Caprice');
// Include the required Google branding
google.search.Search.getBranding('branding');
}
// Set a callback to call your code when the page loads
google.setOnLoadCallback(onLoad);
答案 0 :(得分:2)
您已经检查过搜索结果是否为空:
if (blogSearch.results && blogSearch.results.length > 0) {
您需要做的就是在else
块的结束括号之后添加if
块:
function searchComplete() {
// Check that we got results
document.getElementById('content').innerHTML = '';
if (blogSearch.results && blogSearch.results.length > 0) {
for (var i = 0; i < blogSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = blogSearch.results[i].postUrl;
a.innerHTML = blogSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
document.body.appendChild(p);
}
}
else { // <-- HERE!
document.getElementById("content").innerHTML = "Not found.";
}
}
答案 1 :(得分:0)
if (blogSearch.results && blogSearch.results.length > 0) {
for (var i = 0; i < blogSearch.results.length; i++) {
// Create HTML elements for search results
var p = document.createElement('p');
var a = document.createElement('a');
a.href = blogSearch.results[i].postUrl;
a.innerHTML = blogSearch.results[i].title;
// Append search results to the HTML nodes
p.appendChild(a);
document.body.appendChild(p);
}
} else {
document.getElementById('content').innerHTML = 'Not found!'
}