Pregunta

Here is my code. I want to toggle classes using addClass,for some reasons I don't want to use toggleClass. Problem here I am facing is that css class named selected is added but its not replaced by not_selected.isSelected=0 only indicates that td is selected or not.

<script type="text/javascript"> 


var isSelected = 0;

$("td").click(function(){
    if(isSelected==0)
    {
        $(this).removeClass('not_selected');
        $(this).addClass('selected');
        isSelected=1;
    }

});

$("td").click(function(){
    if(isSelected==1)
    {
        $(this).removeClass('selected');
        $(this).addClass('not_selected');
        isSelected=0;
    }
});

Below is my css code:

.selected
{
    background: black;
    color:white;
    font-weight: bold;
}

.not_selected
{
    background: white;
    color:black;
    font-weight: normal;
}
¿Fue útil?

Solución

Try condensing the two into a single function. It's possible guaranteed (thanks Barmar!) that one handler is running before the other and then automatically switching it back to the undesired one. This way, it will check for isSelected==0 and isSelected==1 in one swoop.

$("td").click(function(){
    if(isSelected==0)
    {
        $(this).removeClass('not_selected');
        $(this).addClass('selected');
        isSelected=1;
    } else if(isSelected==1)
    {
        $(this).removeClass('selected');
        $(this).addClass('not_selected');
        isSelected=0;
    }
});

Otros consejos

Look at this fiddle: http://jsfiddle.net/bukfixart/NYGh5/

The problem is your event handler

$("td").click(function(){
    if(isSelected==0)
    {
        $(this).removeClass('not_selected');
        $(this).addClass('selected');
        isSelected=1;
    } else {
        $(this).removeClass('selected');
        $(this).addClass('not_selected');
        isSelected=0;
    }
});

You should do the whole work in one callback function. not in two. Otherwise the functions are enabling/disabling each other.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top