如何使用jQuery访问属于函数内另一个函数的对象的属性?

时间:2016-04-13 01:11:42

标签: javascript jquery

我正在使用jQuery开发 Tic Tac Toe 游戏。我差不多完成了但仍坚持到底。如何在squareClicked函数的末尾添加代码以检查是否有赢家?如果有,我想将bgreen类仅分配给正方形(tds)。

$('table').on('click', squareClicked);

function squareClicked(e) {
    var $sqr = $(e.target);
    var player = $('.current-player').attr('id');
    if (!$sqr.attr('class')) {
        $sqr.addClass(player + '-marker');
        switchPlayer();
    }
}

function getBoard() {
    var board = [];
    $('td').each(function () {
        board.push(this.className[0]);
    });
    return board;
}

function checkWin() {
    var board = getBoard();
    // array of possible win sets
    var winArray = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8],
        [0, 3, 6], [1, 4, 7], [2, 5, 8],
        [0, 4, 8], [2, 4, 6]];
    var winInfo = {
        win: false
    };
    // loop through the possible win sets
    for (var i = 0; i < winArray.length; i++) {
        // get the marks at the three win locations
        a = board[winArray[i][0]];
        b = board[winArray[i][1]];
        c = board[winArray[i][2]];
        // see if the same marker is at each location
        if (a && a === b && b === c) {
            winInfo.win = true;
            winInfo.play = winArray[i];
            winInfo.winner = a;
            return winInfo;
        }
    }
    return winInfo;
}

JS Fiddle

我在checkWin();函数中调用了squareClicked但它根本没有运行。

2 个答案:

答案 0 :(得分:1)

注意checkWin()返回一个具有3个属性的对象:win,play和winner;将结果分配给变量,然后检查胜利的真实性,以确定玩家是否赢了。

function squareClicked(e) {
    var $sqr = $(e.target);
    var player = $('.current-player').attr('id');
    if (!$sqr.attr('class')) {
        $sqr.addClass(player + '-marker');
        switchPlayer();
    }
    var winInfo = checkWin();
    if (winInfo.win) {
        console.log("You won!");
        // do win stuff  here
    }
}

答案 1 :(得分:1)

function squareClicked(e) {
    var $sqr = $(e.target);
    var player = $('.current-player').attr('id');
    if (!$sqr.attr('class')) {
        $sqr.addClass(player + '-marker');
        switchPlayer();
    }
    var result = checkWin();
    if (result.win){
       // do something here ...
    }
}