+ -
当前位置:首页 → 问答吧 → 如何判断select选项中的值是什么呢?

如何判断select选项中的值是什么呢?

时间:2009-03-21

来源:互联网

//html如下
复制代码
  1. <select style="width:100px;" id="test">
  2.      <option value="pig">pig</option>
  3.     <option value="dog">dog</option>
  4. </select>
  5. <div id="pig" style="dilplay:none">This is a pig.</div>
  6. <div id="dog" style="dilplay:none">>This is a dog.</div>


//js如下
复制代码
  1. $(document).ready(function() {
  2.           $("#test").find("select").change(function(){
  3.                      //判断选中的selected值,   显示对应的层,如何写呢?  
  4.           });
  5. });

作者: coolesting   发布时间: 2009-03-21

$("#test select").change(function() {
       $('#' + $('option:selected', this)).show();
});

没有测试,大概就这样的

作者: wsria.cn   发布时间: 2009-03-21

没反应`~  

作者: coolesting   发布时间: 2009-03-21

$("#test ").change(function() {
       $('#' + $('option:selected', this)).show();
});

作者: seekarmor   发布时间: 2009-03-21

以下的代码应该是你所需要的,下面的代码可以显示对应的层,而隐藏不符合选项的层。
复制代码
  1. <script type="text/javascript">
  2.     $(function(){
  3.         $("#test").change(function(){
  4.             //以下代码是显示符合选择的层。
  5.             var selectedVal = $(this).children('option:selected').attr('value');
  6.             $('#' + selectedVal).show();
  7.             //以下是隐藏不符合选项的层,使用children()函数获取所有子元素,再使用not()函数剔除已经选择的option,再对所有剔除后的元素使用foreach()函数进行取值、隐藏层等操作
  8.             $(this).children().not($(':selected')[0]).each(function(){
  9.                 var unselectedVal = $(this).attr('value');
  10.                 $('#' + unselectedVal).hide();
  11.             });
  12.         });
  13.     })
  14. </script>


另外,楼主的样式设置style="dilplay:none",写错了,应该是display
[ 此帖被巴斯光年在2009-03-22 00:41重新编辑 ]

作者: 巴斯光年   发布时间: 2009-03-22

复制代码
  1. $("#test").find("select").change(function(){
  2. $("#"+$(this).attr("value")).show();
  3. });

作者: aloner   发布时间: 2009-03-22

丫,回答啦。用text()也可以。只不过获取的是文本。

作者: aloner   发布时间: 2009-03-22

$("#" + $("#test").val()).show();

作者: gordianyuan   发布时间: 2009-03-23