Set background colour of select to selected option in JQuery

前端 未结 3 1191
忘掉有多难
忘掉有多难 2020-12-05 20:27

Follow-up to this question: Setting background-color of select options in JQuery

I have a page with multiple select boxes, as per the following:

<         


        
3条回答
  •  长情又很酷
    2020-12-05 21:05

    I like @Arnar Yngvason's answer but I'll add this to the mix. This solution uses CSS classes so the styles can be easily changed without breaking the rest of the code.

    Html

    
    

    CSS

    .Red{background-color:#ff0000;}
    .Blue{background-color:#0000ff;}
    .Green{background-color:#00ff00;}
    .Yellow{background-color:#ffff00;}
    

    JavaScript

    $("select").change(function(){
        $(this).removeClass($(this).attr('class'))
               .addClass($(":selected",this).attr('class')); 
        /*If you want to keep some classes just add them back here*/
        //Optional: $(this).addClass("Classes that should always be on the select");
    
    });
    

     $("select").change(function() {
       $(this).removeClass($(this).attr('class'))
         .addClass($(":selected", this).attr('class'));
       /*If you want to keep some classes just add them back here*/
       //Optional: $(this).addClass("Classes that should always be on the select");
    
     });
        .Red {
          background-color: #ff0000;
        }
        .Blue {
          background-color: #0000ff;
        }
        .Green {
          background-color: #00ff00;
        }
        .Yellow {
          background-color: #ffff00;
        }
    
    
    

    JSFiddle

    I've tested this on FireFox 31, IE 11 and Chrome 37

提交回复
热议问题