私は、基礎を習得するために、ビデオ ポーカー ゲームを JavaScript で作成しようとしていますが、jQuery クリック イベント ハンドラーが複数回実行されるという問題が発生しました。
これらは賭けを行うためのボタンに取り付けられており、ゲーム中の最初のハンドに賭ける場合は問題なく機能します(1 回のみ発動)。ただし、2 番目のハンドに賭ける場合は、賭けまたは賭けを行うボタンが押されるたびにクリック イベントが 2 回発動します(つまり、押すたびに正しい金額の 2 倍が賭けられます)。全体として、賭けボタンを 1 回押したときにクリック イベントが発動される回数については、このパターンに従います。シーケンスの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
クリックが 1 回だけ実行されるようにするには、次を使用します。
$(".bet").unbind().click(function() {
//Stuff
});