Jquery Changing CSS class of object based on numeric content

前端 未结 3 406
粉色の甜心
粉色の甜心 2021-01-25 14:20

Going to be outputting percentages dynamically 0-100%

Want to add CSS class based on percentage. Red for 0% and Blue for 100% progressively.

Markup would be

3条回答
  •  孤街浪徒
    2021-01-25 14:46

    DEMO: http://jsfiddle.net/JAAulde/GJh3j/

    Contains is going to be a pretty expensive query if you have a lot of elements on the page. I would:

    Add a class to all elements:

    100%
    100%
    0%
    100%
    

    Find all those elements, analyze their text, do what you want:

    $( '.percent-holder' ).each( function()
    {
        var $this = $( this ),
            classToAdd = null;
    
        switch( $this.text() )
        {
            case '100%':
                classToAdd = 'blue';
                break;
    
            case '0%':
                classToAdd = 'red';
                break;
        }
    
        if( classToAdd !== null )
        {
            $this.addClass( classToAdd );
        }
    } );
    

提交回复
热议问题