我正在制作一个二十一点游戏来锻炼我的 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);
}
最佳答案
function alertModal(message) {
$popUp = $('.alert-message');
$('.modal').show();
$popUp.text(message);
setTimeout(function() {
$('.modal').fadeOut(1000);
}, 1000);
}
正如评论所解释的那样,fadeOut 在第一次单击后将模式隐藏起来。只需调用 $(element).show();在模式上再次显示它并让 fadeOut 将其删除。
关于javascript - .on ('click' , function(){}) 仅在第一次点击时起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861408/