For this problem I have a snippet of PHP code that looks in a directory and returns a list of files. I then walk through the array and store each file name as a JavaScript variable using echo
Consider the the following example witch does not include the PHP used to generate the image names:
//result of PHP
image1="cow.jpg"
image2="pig.jpg"
image3="dog.jpg"
imgIndex=0 //global variable that will be incremented
function setBG(image) {
someElement.style.backgroundImage= "url(/images/" + image + ")"
};
function nextBG(){
imgIndex++
currentIMG="image"+imgIndex;
setBG(currentIMG);
};
When called function nextBG() will not work. But this will:
function nextBG(){
setBG(image1);
};
I believe the reason it is not working is because the second example is calling the function using the value of the defined variable (cow.jpg). But the first example is calling the function using the string "image1", witch is obviously not a path name for an image.
Is there a way for me to call the function using the variable image1, then image2 and then image3 and so on without it being interpreted as just a string?
Make your variables members of an object. Then you can use [] to access the objects members using a string: