0

小提琴

HTML/CSS 代码与问题无关,大多数 JavaScript 代码也是如此

line 51JavaScript 中,console.log(mode);我期待看到12但我得到undefined. 我唯一的猜测是该值是在内部代码$pregame.on('click', 'button', function () { ...完成其工作之前记录的。

如何在// ------------ game code ------------上面的代码之后运行代码?我有什么选择?


jQuery 代码

(function($) {
    var $pregame = $('div#pregame');
    var $notifier = $('div#notifier')
    var $game = $('div#game');
    var mode;


    for (var i = 0; i < 8; i++) {
        $game.append($('div.frame').eq(0).clone());
    }

    var $frame = $game.find('div.frame');

    $(window).on('resize', function() {
        var windowW = window.innerWidth, windowH = window.innerHeight;
        var gameLen = windowW < windowH * 0.9 ? windowW : windowH * .9;
        $game.css({
            'width':  gameLen + 'px',
            'height': gameLen + 'px'
        });
    }).trigger('resize');

    $pregame.on('click', 'button', function () {

        if ( $(this).data('mode') === 1 ) {
            mode = 1;
        } else {
            var $divs = $notifier.children('div');
            $divs.eq(0).text('Player 1').end().eq(3).text('Player 2');
            mode = 2;
        }

        $pregame.fadeOut(500, function () {
            $game.fadeIn(500);
            $notifier.css('display', 'table').animate({'opacity': 1}, 500);
        });

        $pregame.off('click');
    });

    // ------------ game code ------------

        var activeFrame = 4, gameArray = [];
        for (var i = 0; i < 9; i++) {
            gameArray.push(['-','-','-','-','-','-','-','-','-']);
        }
        console.log(mode); // <<----- THIS HERE <<---------
        if ( mode === 1 ) {
            $('body').on('click', 'div.frame', function() {
                var index = $frame.index(this);
                if ( index === activeFrame ) console.log('click on active Frame');
            });
        } else if ( mode === 2 ) {

        }

})(jQuery);
4

2 回答 2

0

You have it where mode isn't defined until you click the pregame button, it is not called by the time you evaluate mode at line 51.

One solution would be to move the }); on line 42 to line 60. This way, the gamecode section also will not be ran until you click.

于 2013-06-19T11:37:27.347 回答
0

一个让我印象深刻的解决方案是使用回调函数。将游戏代码包装在这样的函数中:

function callMeLater() {
    var activeFrame = 4, gameArray = [];
    for (var i = 0; i < 9; i++) {
        gameArray.push(['-','-','-','-','-','-','-','-','-']);
    }
    console.log(mode); // <<----- THIS HERE <<---------
    if ( mode === 1 ) {
        $('body').on('click', 'div.frame', function() {
            var index = $frame.index(this);
            if ( index === activeFrame ) console.log('click on active Frame');
        });
    } else if ( mode === 2 ) {

    }
}

并从.animate()

$notifier.css('display', 'table').animate({'opacity': 1}, 500, callMeLater);

但这对我来说似乎有点奇怪。我还有其他选择吗?

于 2013-06-19T11:33:50.033 回答