Alator. Alator. - 6 months ago 9
Javascript Question

javascript (jQuery) giving me strange results

Yesterday I started writing code for some random exercise I found on the internet. My task was to have an empty HTML table and, when the user pressed one specific button, it would change the color of the cell to the opposite color (green or red) and change (add or deduct 1) its value. After 10 cell clicks, it should alert a message with the average and some other things. The first time I click the button, everything works fine. However, for subsequent clicks it behaves strangely. Here's some of the code

//.....
var n=0;
$("#b1").click(function(){
document.getElementById("b1").disabled = true;
$("td").removeClass();
for (var i=0; i<25; i++)
{
var z=$("td").eq(i)
z.text(Math.floor((Math.random() * 10) ))
if (z.text()<5)
{
z.addClass("linkClass")
}
else
{
z.addClass("linkClass2")
}
}
$("td").click(function(){
n++;
if ($(this).hasClass("linkClass"))
{
$(this).removeClass()
$(this).text(parseInt($(this).text())-1);
$(this).addClass("linkClass2")
}
else
{
$(this).removeClass()
$(this).text(parseInt($(this).text())+1);
$(this).addClass("linkClass")
}
if (n==10)
{
alert("Ten times clicked");
document.getElementById("b1").disabled = false;
n=0;
}


classes
linkClass
and
linkClass2
are just changing the background color of the cell. Any ideas?

Answer

You should move $("td").click(function(){ out from $("#b1").click(function(){ because each time when you click button you bind one more click on td so it performs several clicks in one time