【发布时间】:2013-02-04 20:53:24
【问题描述】:
我正在尝试用 Javascript 编写一个视频扑克游戏,以了解它的基础知识,但我遇到了一个问题,即 jQuery click 事件处理程序多次触发。
它们附在用于下注的按钮上,在游戏过程中第一手下注时效果很好(仅触发一次);但是在下注秒手时,每次按下下注或下注按钮时,它都会触发两次点击事件(因此每次按下正确的金额都会下注两次)。总的来说,当按下一个投注按钮一次时,点击事件被触发的次数遵循这种模式——其中序列的 ith 项是针对 ith 游戏开始时的手牌: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
}
});
}
如果您有任何想法或建议,或者我的问题的解决方案是否与此处的另一个问题的解决方案相似,请告诉我(我查看了许多类似标题的线程,但没有找到解决方案这可能对我有用)。
【问题讨论】:
-
var amount = parseInt(this.id.replace(/[^\d]/g,''),10);如果您要多次缓存该属性,请不要一直查找它。查找费用很高。 -
感谢您的回复,以及关于缓存属性的提示。我将 player.money 和 player.bet 设置为局部变量 money 并在该函数中下注并操作它们,并将更改我的其余代码也这样做。:) 如果你有时间,你能否解释一下你的建议金额的初始化正在做;它看起来像一些正则表达式,但我不能轻易理解它。
-
@GregoryFowler - 与您的问题无关,但是... javascript switch 语句可能值得研究。
-
伙计,您的函数在每次调用时都会放置一个点击处理程序。如果你在每一轮调用它,在第二轮你有两个处理程序,依此类推。每个处理程序都完成其工作,在第 100 轮时您会收到 100 个警报。
-
发生这种情况是因为在代码中的某处,您重新绑定了事件处理程序,而没有先解除绑定。请参阅此问题以获取 similar scenario 和一个很好的解释。
标签: javascript jquery click jquery-events