j查询单击事件多次触发

2022-08-29 23:48:19

我试图用Javascript编写一个视频扑克游戏,作为获取其基础知识的一种方式,并且我遇到了一个问题,即jQuery点击事件处理程序多次触发。

它们连接到用于下注的按钮上,并且在游戏期间在第一手下注(仅下注一次)可以正常工作;但是在二手牌投注中,每次按下投注或下注按钮时,它都会触发两次点击事件(因此每次按下时,正确的金额是两倍)。总体而言,按下一次下注按钮时,它遵循这种模式来触发点击事件的次数 - 其中序列的第i项是从游戏开始时开始的第i手牌的投注:1,2,4,7,11,16,22,29,37,46,这似乎是n(n + 1)/ 2 + 1,无论价值如何 - 我不够聪明,无法弄清楚, 我使用了OEIS。:)

下面是具有正在执行操作的单击事件处理程序的函数;希望它很容易理解(如果不是,请告诉我,我也想在这方面做得更好):

/** The following function keeps track of bet buttons that are pressed, until place button is pressed to place bet. **/
function pushingBetButtons() {
    $("#money").text("Money left: $" + player.money); // displays money player has left

    $(".bet").click(function() {
        var amount = 0; // holds the amount of money the player bet on this click
        if($(this).attr("id") == "bet1") { // the player just bet $1
            amount = 1;
        } else if($(this).attr("id") == "bet5") { // etc.
            amount = 5;
        } else if($(this).attr("id") == "bet25") {
            amount = 25;
        } else if($(this).attr("id") == "bet100") {
            amount = 100;
        } else if($(this).attr("id") == "bet500") {
            amount = 500;
        } else if($(this).attr("id") == "bet1000") {
            amount = 1000;
        }
        if(player.money >= amount) { // check whether the player has this much to bet
            player.bet += amount; // add what was just bet by clicking that button to the total bet on this hand
            player.money -= amount; // and, of course, subtract it from player's current pot
            $("#money").text("Money left: $" + player.money); // then redisplay what the player has left
        } else {
            alert("You don't have $" + amount + " to bet.");
        }
    });

    $("#place").click(function() {
        if(player.bet == 0) { // player didn't bet anything on this hand
            alert("Please place a bet first.");
        } else {
            $("#card_para").css("display", "block"); // now show the cards
            $(".card").bind("click", cardClicked); // and set up the event handler for the cards
            $("#bet_buttons_para").css("display", "none"); // hide the bet buttons and place bet button
            $("#redraw").css("display", "block"); // and reshow the button for redrawing the hand
            player.bet = 0; // reset the bet for betting on the next hand
            drawNewHand(); // draw the cards
        }
    });
}

如果您有任何想法或建议,或者我的问题的解决方案是否类似于此处另一个问题的解决方案,请告诉我(我已经看过许多类似标题的线程,并且没有运气找到适合我的解决方案)。


答案 1

要确保仅单击一次操作,请使用以下命令:

$(".bet").unbind().click(function() {
    //Stuff
});

答案 2

.unbind()已弃用,您应该改用 .off() 方法。只需在呼叫之前呼叫即可。.off().on()

这将删除所有事件处理程序:

$(element).off().on('click', function() {
    // function body
});

仅删除已注册的“单击”事件处理程序:

$(element).off('click').on('click', function() {
    // function body
});