2010-06-02 33 views
1

我想知道如何添加一個錯誤檢查到下面提到的代碼...我的意思是如何檢查此代碼是否返回空或不?如果這返回空白,那麼我會給一條消息「Not Found」。 我該怎麼做?Javascript幫助需要 - 哪個變量返回空?

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

回答

2

你已經有一個檢查,看看是否在搜索結果空:

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

所有你需要做的只是if塊的右括號後面加一個else塊:

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

十分感謝......我沒有想到的日在......但有一個問題......如果結果返回空,我怎麼隱藏這個div而不顯示? – mathew 2010-06-02 13:12:33

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!' 
}