开发者

jQuery each function only returning last result of total results

I have an object with key : value pair. I'm looping through this object and if the key matches the value that's passed into my function I add it to another variable. The problem is that my c开发者_开发问答ode ends up looping through the results and only adding the last match to my new variable.

function DirectoryOfBusinessSubs(parentID) {
     var myOpt = {"1":"<option>sub1</option>","1":"<option>sub2</option>"};
     var myList;
     $.each(myOpt, function(key, value) {
                    if(key == parentID){
                    myList += value;
                    }
                });
                alert(myList);
                c.append(myList);
        }

If I am passing in 1 for the key, myList should get both sub1 and sub2, but this code is only storing sub2 in myList.


Try this:

function DirectoryOfBusinessSubs(parentID) {
     var myOpt = {"<option>sub1</option>":"1","<option>sub2</option>":"1"};
     var myList = ''; //Fix undefined alert
     $.each(myOpt, function(key, value) {
                    if(value== parentID){
                    myList += key;
                    }
                });
                alert(myList);
                c.append(myList);
        }

THIS MUST DO THE WORK :)


include another scope:

$.each(myOpt, function(key, value) {
                    (function(v){
                      if(key == parentID){
                        myList += v;
                      }
                    })(value);
                });
                alert(myList);
                c.append(myList);
        }

JavaScript closures

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜