jQuery脚本,根据表单选择值显示/隐藏内容 [英] Jquery script which shows/hides content based on form select value

查看:91
本文介绍了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();
  });
})

这篇关于jQuery脚本,根据表单选择值显示/隐藏内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆