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
精彩评论