gpt4 book ai didi

需要 Javascript 帮助 - 哪个变量返回空?

转载 作者:行者123 更新时间:2023-11-30 18:53:34 25 4
gpt4 key购买 nike

我想知道如何为下面提到的代码添加错误检查...我的意思是如何检查此代码是否返回空值??如果这返回为空,那么我会给出一条消息“未找到”..我该怎么做??

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

最佳答案

您已经检查过搜索结果是否为空:

 if (blogSearch.results && blogSearch.results.length > 0) {

您只需在 if block 的右括号之后添加一个 else block :

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.";
}
}

关于需要 Javascript 帮助 - 哪个变量返回空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com