jQuery radio onchange toggle class of parent element?

前端 未结 7 964
无人及你
无人及你 2021-01-11 19:28

Please have a look on the following:

$(\'#myRadio\').change(function() {           

    if($(this).is(\':checked\'))  {
        $(this).parent().addClass(\'         


        
7条回答
  •  执念已碎
    2021-01-11 19:46

    i think this is the best and more flexible way to do this:

    forget the tables (google know many reason for that) and use wrappers like below

    format with CSS like this

    span.radio {
        background-color: #cccccc;
    }
    span.currentGreen {
        background-color: #ccffcc;
    }
    

    and using this script you can do exactly the same as you want

    $('.myRadio').change(function() {           
        $('.currentGreen').removeClass('currentGreen'); // remove from all
        if ($(this).is(':checked')) {
            $(this).parent().addClass('currentGreen'); // add to current
        }
    });
    

    i don't like to use filter() and find() because they use unnecessary resources in this case.

提交回复
热议问题