I have a variable that contains an image path. Depending on what integer value I receive for a JSON object, this variable is supposed to get a different path.
However, for some reason within the function below, the path assigned to the variable remains to be the one globally declared, despite the fact that I know for a fact that my JSON object's is returning the right integer for a switch statement. Take a look at the code below:
function spawnThumbnails() {
$.getJSON('scripts/get_thumbs.php', function(data){
$.each(data, function(thumb, thumbInfo){
var thumbimage;
// If I create local thumbimage var like so,
//the image below turns is undefined
// But if local thumbimage var is not declared,
// the value defaults to globally declared value of arctic.svg
var thumbtype = thumbInfo.type;
alert(thumbtype); // this will alert correct type (an integer)
switch(thumbtype){
case 1: thumbimage = 'graphics/thumbs/arctic.svg'; break;
case 2: thumbimage = 'graphics/thumbs/savan.svg'; break;
case 3: thumbimage = 'graphics/thumbs/trop.svg'; break;
case 4: thumbimage = 'graphics/thumbs/tundra.svg'; break;
case 5: thumbimage = 'graphics/thumbs/ocea.svg'; break;
}
$("#thumbtest").append('<img src="' + thumbimage + '">');
// returning as the default image or undefined
}); //end each
}); // end json
}
var thumbimage = 'graphics/thumbs/artic.svg'; // default image
// I have tried placing the function definition here as well,
// but there is no difference. Should there be?
spawnThumbnails();
I am kind of new to javascript function scopes and such. Am I right in thinking that I should be able to declare the function before the function call and the global variable declaration?
I also find it strange that I do not have to declare a "thumbimage" parameter in the spawnThumbnails function declaration. In fact, if I do declare a parameter, it breaks. But I am guessing this is because it creates a new local variable, am I right?
Thanks for any help! in advance