Salve ho una pagina del tris dove il click delle caselle è gestito tramite e.target, quello che vorrei fare è gestire il click delle caselle con l'evento onclick ma non saprei come fare. Allego il link della pagina http://lyokocode.altervista.org/Tris-js.html e il codice della pagina:
codice:
function TicTacToe(selector) {
var main_element = $(selector)[0],
score_X = $('.score.X')[0],
score_O = $('.score.O')[0],
board = $('.board')[0],
grid_options = $('.grid-options')[0],
reset_btn = $('.btn-reset')[0];
var grid_size = 3,
moves = 0,
scores = {
X: 0,
O: 0
},
data = {};
$('.grid-options').change(function(e) {
grid_size = $(this).val();
init();
});
init();
$('.btn-reset').click(function(e) {
reset_btn = init();
});
function paint() {
var table = '<table>';
for (var i = 0; i < grid_size; i++) {
table += '<tr>';
for (var j = 0; j < grid_size; j++) {
table += '<td row="' + i + '" column="' + j + '"></td>';
}
table += "</tr>";
}
$(board).html(table);
var columns = $('td');
for (i = 0; i < columns.length; i++) {
$(columns[i]).click(function(e) {
td = mark(e);
})
}
}
function mark(e) {
var evt = e || event;
var td = evt.target || evt.srcElement;
if ($(td).html()) {
return;
}
var row = $(td).attr('row'),
column = $(td).attr('column');
var current_mark = moves % 2 === 0
? 'X'
: 'O';
$(td).html(current_mark);
$(td).addClass(current_mark);
data[row + '' + column] = current_mark;
moves++;
if (didWin(current_mark)) {
alert(current_mark + ' vince la partita!');
scores[current_mark]++;
updateScoreboard();
empty();
} else if (moves === Math.pow(grid_size, 2)) {
alert("Pareggio!");
empty();
}
}
function didWin(mark) {
var vertical_count = 0,
horizontal_count = 0,
right_to_left_count = 0,
left_to_right_count = 0;
for (var i = 0; i < grid_size; i++) {
vertical_count = 0;
horizontal_count = 0;
for (var j = 0; j < grid_size; j++) {
if (data[i + '' + j] == mark) {
horizontal_count++;
}
if (data[j + '' + i] == mark) {
vertical_count++;
}
}
if (data[i + '' + i] == mark) {
left_to_right_count++;
}
if (data[(grid_size - 1 - i) + '' + i] == mark) {
right_to_left_count++;
}
if (horizontal_count == grid_size || vertical_count == grid_size) {
return true;
}
}
if (left_to_right_count == grid_size || right_to_left_count == grid_size) {
return true;
}
return false;
}
function empty() {
moves = 0;
paint();
data = {};
}
function init() {
empty();
scores = {
X: 0,
O: 0
};
updateScoreboard();
}
function updateScoreboard() {
$('.score.X').html(scores.X);
$('.score.O').html(scores.O);
}
}
codice:
TicTacToe('.game-panel');
Nel codice var td = evt.target || evt.srcElement è gestito tramite e.target ma non saprei come farlo tramite evento onclick.