i未从0开始

人气:800 发布:2022-09-11 标签: javascript ajax firefox

问题描述

这code提示测试1,则提醒8!

This code alerts 'test 1', then alerts 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);

为什么和如何解决?

Why and how to solve?

推荐答案

我以前曾经有过这样的问题在IE中。你应该总是使用 VAR 循环,以确保是本地范围:

I've had problems like this in IE before. You should always use the var in a for loop to make sure i is locally scoped:

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

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

Unless you declare the variable beforehand in the same scope:

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

另请参阅:

http://stackoverflow.com/questions/790558/variable-scope-in-javascript-for-loop/790572 http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/Var

914