first of all, sorry for my bad english :( I have a function, that function shuffle the cards i have and creates the DIVS with the images I need to have one event for all these divs my code is:
//shuffles the cards
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
//output += '<div class="container" id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
var img = memory_array[i];
var tile = 'tile_' +i
var div = document.createElement('div');
div.className='container';
div.id=tile;
div.addEventListener('click',function(){
memoryFlipTile(tile,img)},false);
document.getElementById('memory_board').appendChild(div);
}
//document.getElementById('memory_board').innerHTML = output;
}
function score(){
var level = $('.level').text();
puntuacion = puntuacion + (10 * level);
$('.score').text(puntuacion);
}
//compare cards
function memoryFlipTile(tile,val){
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.backgroundImage = "url('bagels/"+val+"')"
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
for(var j = 0; j<memory_tile_ids;j++ ){
alert($('#' + memory_tile_ids[j]));
$('#' + memory_tile_ids[j]).unbind('click');
}
score();
tiles_flipped += 2;
// Vaciamos los 2 arrays
memory_values = [];
memory_tile_ids = [];
// Comprobamos que todas las cartas se han girado correntamente y empezamos un nuevo nivel
if(tiles_flipped == memory_array.length){
/*document.getElementById('memory_board').innerHTML = "";
newBoard();*/
}
} else {
function flip2Back(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(carta.png) no-repeat';
tile_2.style.background = 'url(carta.png) no-repeat';
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 500);
}
}
}
}
I solved it using the following jQuery code
memory_array.memory_tile_shuffle();
var $board = $('#memory_board');
$.each(memory_array, function(i, v) {
var id = 'tile_' + i;
var card_tpl = '<div class="container" id="'+id +'"></div>';
$(card_tpl)
.on('click', function() {
memoryFlipTile(this, memory_array[i]);
})
.attr('id', id).appendTo($board);
});
var $board = $('#memory_board');
$.each(memory_array, function(i, v) {
var id = 'tile_' + i;
var card_tpl = '<div class="container" id="'+id +'"></div>';
$(card_tpl)
.on('click', function() {
memoryFlipTile(this, memory_array[i]);
})
.attr('id', id).appendTo($board);
});
Here its the app: http://juego.adrianpyjavierr.hol.es/juego.html