开发者

Javascript scope question - chrome extension

开发者 https://www.devze.com 2023-01-08 10:40 出处:网络
for(var p = 0; p < xmls.length; p++) { var feed = new google.feeds.Feed(xmls[p]); feed.load(fu开发者_如何学Gonction(result) {
for(var p = 0; p < xmls.length; p++) {
    var feed = new google.feeds.Feed(xmls[p]);
    feed.load(fu开发者_如何学Gonction(result) {
//code

In the above code, if I output p outside of the feed.load function, I correctly see that p iterates. However, if I output p inside that function (where I need to access it), It remains at 2 (which happens to be the length of the array "xmls"). I know this is a scope issue, but not how to fix it.

Thanks in advance!


You need to create a new scope, which means a new function.

for(var p = 0; p < xmls.length; p++) {
    (function(p) {
         var feed = new google.feeds.Feed(xmls[p]);
         feed.load(function(result) {
                       // use p
         });
     })(p);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消