質問

Currently I'm working on a card game application using a combination of PHP and JavaScript. I'm running into a problem with my event handling however. The functionality I want is for a player to be able to click on a card, then a message is displayed instructing to click the card again to flip it over. Here's my basic setup:

function flipPlayerCard($card) {
    gameAlert('Click the card again if you would like to flip it.');
    $compareCard = $card;
    $('body').off().on('click', '.card', function() {
        if ($compareCard.attr('id') == $(this).attr('id')) {
                    console.log('Flipping card');
            //Call the flip player card function
        }
        else {
            gameAlert('');
            resetBinds();
        }
    });
}
function resetBinds() {
    $('body').off().find('.player').eq(turn).find('.card').add('.draw_pile .card').add('.discard_pile .card').on('click', function(event) {
        event.stopPropagation();
        cardSwitch($(this));
    });
}
function cardSwitch($this) {
    $('body').off();
    var type = $this.parent().parent().attr('class');
    switch (type) {
        case 'player':
            flipPlayerCard($this);
            break;
        case 'discard_pile':
            takeDiscardPileCard();
            break;
        case 'draw_pile':
            flipDrawPileCard();
            break;
    }
}
$(document).ready(function() {
    resetBinds();
});

On the first click it works fine, but on the second click nothing is logged to the console. I know there has to be a better way to handle these chained events like this. What am I missing? Any help is appreciated.

役に立ちましたか?

解決

something simpler might be

function flipPlayerCard( card ) {

    if ( card.hasClass('clicked') ) {
       // code to flip the card
       card.removeClass('clicked');
    } else {
       $('.clicked').removeClass('clicked'); // if clicked on new one, clear old
       card.addClass('clicked');
       gameAlert('Click the card again if you would like to flip it.');
    }
}

this way you don't need to reset your event bindings

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top