我不是从0开始

时间:2010-02-19 00:12:45

标签: javascript ajax firefox

此代码警告'test 1',然后警告8!

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

为什么以及如何解决?

3 个答案:

答案 0 :(得分:4)

之前我在IE中遇到过这样的问题。您应该始终使用var循环中的for来确保i是本地范围的:

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

除非您事先在同一范围内声明变量:

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

另见:

Variable scope in Javascript for loop
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/Var

答案 1 :(得分:1)

你有没有其他警报,没有粘贴在那里?如果您将其更改为:

,该怎么办?
alert('test 1, gclasses.length = '+gclasses.length);
for (var i = 0; i < gclasses.length; i++) {
    alert(i);

我想知道该循环是否正在执行?

答案 2 :(得分:1)

在您使用它的每个函数中本地声明变量(在这种情况下为i)。如果为变量赋值(即使使用for循环),它也会变为全局变量,并且可能会同时运行其他函数。