【问题标题】:How to show/hide div when we select 'all' option当我们选择“全部”选项时如何显示/隐藏 div
【发布时间】:2019-04-26 01:31:17
【问题描述】:

我有一个小要求。我需要根据选择的选项显示和隐藏 div。下面是我的代码。当我选择“全部”选项时,何显示所有绿色和红色类 div。它适用于红色和绿色选项。提前致谢。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="colorselector">
            <option>Choose Color</option>
            <option value="all">All</option>
    		<option value="red">Red</option>
            <option value="green">Green</option>
    </select>
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>


<script type="text/javascript">
$(function() {
  $('#colorselector').change(function(){
    $('.box').hide();
    $('.' + $(this).val()).show();
	
  });
});
</script>


    .box{
        color: #fff;
        display: none;
        margin-top: 20px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }

【问题讨论】:

  • 关闭选民:这不是提议的副本的副本。与这个问题一样,建议的副本是一个调试问题。虽然提议的副本的标题看起来可能是重复的,但这两个问题中的问题完全不同。

标签: jquery


【解决方案1】:

试试这个代码:

<select id="colorselector">
            <option>Choose Color</option>
            <option value="all">All</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
    </select>
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>

脚本:

<script type="text/javascript">
$(function() {
 $('#colorselector').on('change', function() {
  var data = $(this).val();
 if( data =='red')
 {
  $('.green').hide();
  $('.red').show();
 }
 else if($(this).val() =='green')
 {
  $('.green').show();
  $('.red').hide();
 }
 else
 {
  $('.green').show();
  $('.red').show();
 }
});
});
</script>

【讨论】:

  • 感谢您抽出时间 Bhoomi,但我的问题不同。
  • 当我选择红色选项时,它只显示红色类,绿色选项它只显示绿色类,当我选择所有选项时,它应该同时显示红色和绿色类。
  • 是的,它有效,谢谢 Bhoomi。这里代码中的小改动 -- if( data =='red') { $('.green').hide(); $('.red').show(); }
【解决方案2】:

使用 if 语句来检测用户是否选择了“全部”。请检查以下代码。

$(function() {
  $('#colorselector').change(function(){

    $('.box').hide();

    //if user is selecting 'all', show all boxes
    if($(this).val() == 'all'){

        $('.box').show()

    //otherwise only show the color they select
    } else {

      $('.' + $(this).val()).show();

    }


  });
});

这是一个有效的JS Fiddle Example

【讨论】:

  • 感谢您抽出时间Shehara。
  • 没问题,如果成功请选择作为答案,谢谢
【解决方案3】:

由于您只有一个“全部”选项,因此您可以执行“如果”来检查该选项是否被按下:

$(function() {
  $('#colorselector').change(function(){
    if($(this).val()=="all"){
      $('.box').show();
    }else{
      $('.box').hide();
      $('.' + $(this).val()).show();
    }
  });
});

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多