开发者

Why the addClass is not working in this code

开发者 https://www.devze.com 2023-04-08 02:36 出处:网络
In the below Code of my function when i use CSS it works fine. when I add this CSS to a class it is not working

In the below Code of my function when i use CSS it works fine. when I add this CSS to a class it is not working

function setTab(selection) {
        $("#"+selection).css开发者_C百科('background', '#CC0000');
        $("#"+selection).css('color', '#ffffff');   
        // Both the Above statements works fine     
        $("#"+selection).addClass("selectedclass");//doesnot work 
    }   

    .selectedclass li{
        background: #CC0000;
        color: #ffffff;
    }


What I bet is happening is that the class is being overruled by another style. Which is the the most obvious in this case. The reason the first two lines of code work is becaue they edit the style directly, where adding a class, the cascading rules still would apply

Try these:

<style type="text/css">
    /* I'm guess at what I think you need, since I don't know your HTML structure. */
    body .selectedclass li,
    body ul .selectedclass li ,
    body ol .selectedclass li {
        background: #CC0000;
        color: #ffffff;
    }
</style>

Your code is simple, so it's probably correct. But you could clean it up a bit like so:

function setTab(selection)
{
    if ( typeof(selection) == "string" )
    {
        $( '#' + selection ).addClass( "selectedclass" );
    }
}   


Is it possible that there is a more specific selector than the class selector being applied? Have you looked at the element in Firebug to see where the element is getting its properties? Using the first two statements, you're setting the style directly on the element, which will take precedence. Using the second, it will depend on the various styles that you have defined, their order and specificity. Could also be that your class is applied to the wrong element, i.e., directly to the li instead of the parent ul (ol). In that case you need to change your rule to li.selectedClass.

Also, did you know that you can chain the jQuery functions together? And css has an overload that takes a map of key/value pairs.

function setTab(selection) {
    $("#"+selection).css({'background-color': '#CC0000', 'color' : '#ffffff'});
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号