I'm trying to make a little rock paper scissors game. for that I've written a small javascript in jquery. the whole thing should work like this: user presses button, an ajax event is fired, the selected option is added to a div and a counter increments. but only 3 times! I can't figure it out to work like this... here's my code
if (counter <= 3){
$('.buStein1').click(function(event){
$.post("game.php", { uid: "<?php echo $user['id']?>", choice: "stein", runde: counter });
$('#choiceContainer').append(stein);
counter++;
});
$('.buSchere1').click(function(event){
$.post("game.php", { uid: "<?php echo $user['id']?>", choice: "schere", runde: counter });
$('#choiceContainer').append(schere);
counter++;
});
$('.buPapier1').click(function(event){
$.post("game.php", { uid: "<?php echo $开发者_Go百科user['id']?>", choice: "papier", runde: counter });
$('#choiceContainer').append(papier);
counter++;
});
}
else {
$('#choiceContainer').text('no clicking possible');
}
First of all define your counter outside the functions:
var counter = 0;
Then check counter within the click event handlers prior to doing anything else:
$('.buStein1').click(function(event){
if (checkCounter()) {
$.post("game.php", { uid: "<?php echo $user['id']?>", choice: "stein", runde: counter });
$('#choiceContainer').append(stein);
}
});
$('.buSchere1').click(function(event){
if (checkCounter()) {
$.post("game.php", { uid: "<?php echo $user['id']?>", choice: "schere", runde: counter });
$('#choiceContainer').append(schere);
}
});
$('.buPapier1').click(function(event){
if (checkCounter()) {
$.post("game.php", { uid: "<?php echo $user['id']?>", choice: "papier", runde: counter });
$('#choiceContainer').append(papier);
}
});
function checkCounter()
{
if (counter > 3)
{
$('#choiceContainer').text('no clicking possible');
return false;
}
counter++;
return true;
}
The if (counter <= 3)
check should be inside the click
function.
At the moment you're binding the click event if the counter is less than three.
精彩评论