2010-02-19 79 views
1

此代碼提醒'測試1',然後提醒8!我並非從0開始

uri = 'http://www.scriptcopy.com/'; 
compareuris = new Array(); 
compareuris[0] = 'http://www.scriptcopy.com/'; 
compareuris[1] = 'https://www.scriptcopy.com/'; 
compareuris[2] = 'http://www.www.scriptcopy.com/'; 
compareuris[3] = 'https://www.www.scriptcopy.com/'; 
compareuris[4] = 'http://scriptcopy.com/'; 
compareuris[5] = 'https://scriptcopy.com/'; 
compareuris[6] = 'http://www.scriptcopy.com/'; 
compareuris[7] = 'https://www.scriptcopy.com/'; 
searchuri = 'http://www.google.com/search?'; 
searchuri += 'q='+ encodeURIComponent(uri) +'&btnG=Search+Directory&hl=en&cat=gwd%2FTop'; 
req = new XMLHttpRequest(); 
req.open('GET', searchuri, true); 
req.onreadystatechange = function (aEvt) { 
    if (req.readyState == 4) { 
     if(req.status == 200) { 
      searchcontents = req.responseText; 
      parsedHTML = sc_HTMLParser(searchcontents); 
      sitefound = sc_sitefound(compareuris, parsedHTML); 
     } 
    } 
} 
req.send(null); 
function sc_HTMLParser(aHTMLString){ 
    var parseDOM = content.document.createElement('div'); 
    parseDOM.appendChild(Components.classes['@mozilla.org/feed-unescapehtml;1'] 
     .getService(Components.interfaces.nsIScriptableUnescapeHTML) 
     .parseFragment(aHTMLString, false, null, parseDOM)); 
    return parseDOM; 
} 
function sc_sitefound(compareuris, parsedHTML) { 
    gclasses = parsedHTML.getElementsByClassName('g'); 
    alert('test 1'); 
    for (i = 0; i < gclasses.length; i++) { 
     alert(i); 
     gclass = gclasses[i]; 
     atags = gclass.getElementsByTagName('a'); 
     tag1 = atags[0]; 
     hrefattribute1 = tag1.getAttribute('href'); 
     uri1 = hrefattribute1; 
     compareduris = sc_compareuris(uri1, compareuris); 
     alert('test 2'); 
     if (compareduris) { 
      sitefound = uri1; 
      return sitefound; 
      alert('test 3'); 
     } 
     alert('test 4'); 
    } 
    return null; 
} 
function sc_compareuris(uri, compareuris) { 
    for (i = 0; i < compareuris.length; i++) { 
     compareuri = compareuris[i]; 
     if (uri == compareuri) { 
      return true; 
     } 
    } 
    return false; 
} 

聚焦:

alert('test 1'); 
    for (i = 0; i < gclasses.length; i++) { 
     alert(i); 

爲什麼和如何解決?

+1

首先通過JSLint運行它:「問題在第23行字符2:缺少分號。」 – 2010-02-19 00:18:30

回答

1

你有沒有其他的提醒,沒有粘貼?如果將其更改爲:

alert('test 1, gclasses.length = '+gclasses.length); 
for (var i = 0; i < gclasses.length; i++) { 
    alert(i); 

我想知道該循環是否正在執行?

1

在您使用的每個函數中聲明本地變量(本例中爲i)。如果你給一個變量賦值(即使是for循環),它也會變成一個全局變量,並且可能會同時運行其他函數。