jQuery脚本,根据表单选择值显示/隐藏内容

问题描述:

我正在尝试实现一个我发现的jquery脚本,该脚本可根据表单中下拉字段的选择值来显示/隐藏内容.

I am trying to implement a jquery script that I found which enables content to be displayed/hidden dependent on the select value of a dropdown field in a form.

它可以扩展,但是我需要做的是在加载页面时隐藏所有内容,并且仅根据选择值显示相关内容.目前,它显示了页面加载时的所有内容,然后可以正常工作以按我选择的值显示/隐藏内容.

It works to an extend but what I need it to do is to hide all the content when the page is loaded and only display the relevant content dependent on the select value. At the moment it is showing all the content when the page is loaded and then works fine to show/hide content as expected when I select a value.

如何在第一个实例中隐藏所有内容?

How can I hide all content in the first instance?

以下是我到目前为止通过测试得到的内容:

<select id="viewSelector">
<option value="0">-- Select a View --</option>       
<option value="view1">view1</option>
<option value="view2">view2</option>
<option value="view3">view3</option>
</select>

<div id="view1">
<p>a</p> 
</div>
<div id="view2a">
<p>b</p> 
</div>
<div id="view2b">
<p>c</p> 
</div>
<div id="view3">
<p>d</p> 
</div>

而jQuery是:

$(document).ready(function() {
$.viewMap = {
    '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3' : $('#view3')
  };

  $('#viewSelector').change(function() {
    // hide all
    $.each($.viewMap, function() { this.hide(); });
    // show current
    $.viewMap[$(this).val()].show();
  });
});

这是测试页的链接,因此您可以了解我的意思:

Here is link to the test page so you can see what I mean:

http://sitesforasnip.com/form/testform.html

非常感谢

我对您的代码进行了一些编辑.

I have edited your code a bit.

我为您创建了一个jsfiddle.这会有所帮助. http://jsfiddle.net/gGRmR/

I have created a jsfiddle for you. This will help. http://jsfiddle.net/gGRmR/

$(document).ready(function(){

    $('#view1').hide();
    $('#view2a').hide();
    $('#view2b').hide();
    $('#view3').hide();
$.viewMap = {
    '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3' : $('#view3')
  };

  $('#viewSelector').change(function() {
    // hide all
    $.each($.viewMap, function() { this.hide(); });
    // show current
    $.viewMap[$(this).val()].show();
  });
})