tags:

views:

74

answers:

2

I'm teaching myself jQuery by writing the game of memory (where you turn tiles over two at a time, looking for matches).

I have 16 img tags, each representing one of the tile faces. I have an array of 16 jpg file names. I want to set the src attribute of each img tag to a random selection from my array. To do so, I wrote a function that extracts a string from the array, removes the string from the array, and returns the string. I then use this function in the onReady handler this way:

$('.picture').attr( {src : extractArrayValue(cousinPictures)});

This seems to work, except that it appears that the function extractArrayValue appears to be called only once across all 16 tags. All 16 img tags get the same image, but if I refresh the page they get a different same 16 image files.

Am I correct about what's happening? And, if so, is there a straightforward way to force extractArrayValue to get called for each attribute that gets set?

+5  A: 

You simply need to enumerate the pictures.

$('.picture').each(function() {
    this.src = extractArrayValue(cousinPictures); 
});

If you want to understand why 'this' is the image check out this link.

function.apply(this_context, arguments)

ChaosPandion
Thanks, that's exactly what I needed to know. Would you care to explain (since this is a learning project for me) how the "this" reference is present in the anonymous function passed to each()?
Larry Lustig
+1  A: 

You may need to run it through an each function, maybe provide more of your code, but i think you need:

$('.picture').each(function(){
    $(this).attr({src: extractArrayValue(cousinPictures)});
});
Jojo