如何在某个选项值的div上添加一个类

时间:2013-09-26 18:35:48

标签: jquery html switch-statement option addclass

我想知道如果选项的值已选中,如何将一个类添加到div。例如,我正在为我堂兄的业务制作一个网站,我们想要一个简单的方法来改变菜单。

<code>
         <div id="select"><form>
         Menu:
         <select name="select" class="form-control">

           <option value="drinks">Drinks</option>
           <option value="breakfast">Breakfast</option>
         </select>
        <input type="submit" value="Submit">
         </form>
</code>

我想如果值是早餐来隐藏div drinks并显示div breakfast,并且还让它可逆。谢谢,这是我在JSFiddle http://jsfiddle.net/t5R9s/

上的代码

2 个答案:

答案 0 :(得分:1)

您可以使用javascript。当你点击提交或刚做完选择后,你想要这样做吗?

[

Fiddle

<script type="text/javascript">
function changeClass(){
    var myVariable = document.getElementById('control').value;
    if(myVariable == "drinks"){
        document.getElementById('drinks').className = "";
        document.getElementById('breakfast').className = "hide";
    }
    else if(myVariable == "breakfast"){
        document.getElementById('drinks').className = "hide";
        document.getElementById('breakfast').className = "";
    }
}
</script>
<div id="select">
    <form>Menu:
        <select name="select" class="form-control" id="control" onChange="changeClass()">
            <option value="drinks">Drinks</option>
            <option value="breakfast">Breakfast</option>
        </select>
    </form>
</div>
<div id="drinks">
     <h2 align="center">Drinks</h2>

    <table width="888" border="" cellpadding="9" class="">..</table>
</div>
<!--Breakfast table-->
<div id="breakfast" class="hide">
        <h2 align="center">Breakfast</h2>

    <table width="888" border="" cellpadding="9" class="">..</table>
</div>

答案 1 :(得分:1)

这是

$(document).ready(function() {
 $(".form-control").change(function() {
  if($(this).val() == "drinks") {
    $("#drinks").show();
    $("#breakfast").hide();
  } else {
    $("#drinks").hide();
    $("#breakfast").show();
  }
 });
});

这是FIDDLE