문제

I have 3 possible class combinations that can be applied to an element, for our sake the classes are

".a" and ".b"

sometimes both .a and .b can be applied or sometimes just .a and sometimes no classes at all. I want to write an if statement that catches all 3 possible combinations for example

if (node.hasClass("a")){
//do something
}else if(node.hasClass("a") && node.hasClass("b")){
//do something different
}else{
//some something else all together
};

But right now this if statement is not working, any suggestions?

Thanks!

** hasClass(); is a YUI3 method

도움이 되었습니까?

해결책

You always need to "catch" the most restrictive case first. So change your logic to:

if (node.hasClass("a") && node.hasClass("b")){
//do something
}else if(node.hasClass("a")){
//do something different
}else{
//some something else all together
};

다른 팁

Your original code doesn't work because if the node has class a (regardless of whether or not it also has class b), it will enter the first block, and never check the other conditions.

Try this instead:

if (node.hasClass("a")) {
    if(node.hasClass("b")) {
        // has a and b
    } else {
        // has a only
    }
} else {
    // does not have a
};
if(node.hasClass("a") && node.hasClass("b"))
{
    //both .a and .b
}
else if(node.hasClass("a"))
{
    //only .a
}
else if(node.hasClass("b"))
{
    //only .b
}
else
{
    //neither
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top