.on('click',function(){})仅在首次点击时起作用

我正在制作二十一点游戏以锻炼我的Javascript技能。我有一堆alert()消息与投注功能相关联,以防止输入无效。在更新代码以使其具有比浏览器警报更优雅的消息样式时,我编写了一个名为alertModal()的函数,该函数在屏幕上弹出一条消息,然后逐渐消失。用户首次尝试输入无效的投注时会弹出该消息,但如果该投注无效,则不会弹出任何其他消息-不会发生任何事情。我知道当用户再次单击时placeBet()函数仍在运行,因为如果下注有效,则dealFirstCards()将运行并且游戏继续进行。因此在我看来,由于某种原因,placeBet()函数的if / else部分仅在第一次单击时运行...

该游戏可以在http://cnb-blackjack.netlify.com/game.html上使用此代码运行并运行

这是有问题的javascript代码:


// Player places a bet
    $('div.bet').on('click',function() {
        $(this).removeclass('glow');
        $('.bet-button').addClass('glow');
    });
    $('.bet-button').on('click',function() {
        event.preventDefault();
        if (!placeBet.called) {
            placeBet();
        }
    });

// PLACE BET
    function placeBet() {
        var $bet = parseInt($('.bet-input').val())
        var $bank = parseInt($('.player-bank').text())
        var $currentBet = $('.current-bet');
        if (!isnaN($bet) && $bet <= $bank && $bet !== 0) {
            $currentBet.text(' $' + $bet);
            $('.bet input[type="text"]').val('');
            $('.place-bet .hideaway').slideup();
            $('.player-bank').text($bank - $bet);
            placeBet.called = true;
            dealFirstCards();
        } else if ($bet > $bank) {
            var $message = 'Bet cannot exceed the amount in your Bank!';
            alertModal($message);
        } else if (isnaN($bet)) {
            var $message = 'Enter a number,without "$".';
            alertModal($message);
        } else if ($bet === 0) {
            var $message = "Betting nothing won't get you very far...";
            alertModal($message);
        }
    }

// SHOW MODAL
    function alertModal(message) {
        $popUp = $('.alert-message');
        $('.modal').removeclass('hide');
        $popUp.text(message);
        setTimeout(function() {
            $('.modal').fadeOut(1000);
        },1000);
    }
sinochun 回答:.on('click',function(){})仅在首次点击时起作用

function alertModal(message) {

        $popUp = $('.alert-message');
        $('.modal').show();
        $popUp.text(message);
        setTimeout(function() {
            $('.modal').fadeOut(1000);
        },1000);
    }

正如评论所解释的,fadeOut在第一次单击后将其隐藏起来。只需调用$(element).show();在模式上再次显示它,然后让fadeOut将其删除。

本文链接:https://www.f2er.com/3100921.html

大家都在问