Div css change when select option is selected with jQuery

限于喜欢 提交于 2019-12-11 14:48:54

问题


I have come close to the answer but I am not good enough at jQuery to tweak it to get it the way I want.

I need to change the css class of a div when a select option is selected.
So if the code was:

<style>
  .red{
  background-color:red;
}
  .green{
  background-color:green;
}
  .blue{
  background-color:blue;
}
</style>

<html>

<div id="box"> </div>

<select>
  <option value=1>Red</option>
  <option value=2>Green</option>
  <option value=3>Blue</option>
</select>

</html>

How would I go about changing the background colour of "#box" when the appropriate option is selected?

THIS was so, so close. (Found here)


回答1:


$('select').change(function(){
    $('#box').removeClass('red green blue').addClass(
        $(this).find('option:selected').text().toLowerCase()
    );
})
.change();

Here's the fiddle: http://jsfiddle.net/aHYKG/



来源:https://stackoverflow.com/questions/9024516/div-css-change-when-select-option-is-selected-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!