1

我在应用 jquery 的下拉效果来显示表单字段的隐藏 div 时遇到问题。如果从选择下拉列表中选择了特定值,我将尝试显示每组表单字段。

脚本:

$(document).ready(function(){
       $("#role").change(function(){
        if ($("#role").val() == "student" ){ 
            $(".hide1").slideDown("fast"); //Slide Down Effect
        } else {
            $(".hide1").slideUp("fast");    //Slide Up Effect
        }
        if ($("#role").val() == "faculty" ) {
            $(".hide2").slideDown("fast"); //Slide Down Effect
        } else {
            $(".hide2").slideUp("fast");    //Slide Up Effect 
        }
         if ($("#role").val() == "alumni" ) {
            $(".hide3").slideDown("fast"); //Slide Down Effect 
        } else {
             $(".hide3").slideUp("fast");    //Slide Up Effect
        }});
});

HTML:

<form id="myform" class="form-control">
  <select name = "role" class = "btn btn-primary" id ="role">:
    <option>Role</option>
    <option value = "student"> Student </option>
    <option value = "faculty"> Faculty/Staff </option>
    <option value = "alumni"> Alumni </option>
  </select>
  <br/><br/><br/><br/><br/><br/>
  <div class="hide" id ="hide1">
    <label for="address">Campus Address:</label>
    <input type="text" id = "campadd" name="campadd" class= "form-control"/>
    <label for="Major">Major:</label>
    <input type="text" id = "major" name="major" class= "form-control"/>
  </div>
  <div class="hide" id = "hide2">
    <label for="department">Department:</label>
    <input type="text" id = "dept" name="dept" class= "form-control"/>
    <label for="location">Location:</label>
    <input type="text" id = "locations" name="location" class= "form-control"/>
  </div>
  <div class="hide" id ="hide3">
    <label for="graduationdate">Graduation Year:</label>
    <input type="text" id = "gradyear" name="gradyear" class= "form-control"/>
    <label for="Major">Degree:</label>
    <input type="text" id = "degree" name="degree" class= "form-control"/>
  </div>
  <br/>
</form>
4

1 回答 1

4

您在上滑/下滑命令中使用类选择器而不是 id 选择器

$(".hide2").slideDown("fast");

代替

$("#hide2").slideDown("fast");

它可以缩短为

$(document).ready(function () {

    var map = {
        student : '#hide1',
        faculty : '#hide2',
        alumni : '#hide3',
    }
    $("#role").change(function () {
        var target = $(map[this.value]);
        $('.hide').not(target).stop(true, true).slideUp("fast");
        target.stop(true, true).slideDown("fast");
    });
});

演示:小提琴

另一种看待这个的方式是:小提琴

于 2013-10-12T16:29:57.980 回答