【问题标题】:How can I improve my jQuery show/hide implementation?如何改进我的 jQuery 显示/隐藏实现?
【发布时间】:2012-12-17 16:35:25
【问题描述】:

我正在使用以下内容来显示和隐藏 div。它有效,但我不禁认为它可以更有效。在简化的示例中,我展示了 3 个国家/地区,但我的代码需要处理几十个。我对 jQuery 很陌生。有没有办法只说“点击时显示任何国家,并隐藏其余国家”?

HTML

<div class="nav">
    <span id="France">France</span>
    <span id="Canada">Canada</span>
    <span id="Portugal">Portugal</span>
</div>

<!-- show div based on which span is clicked; hide the rest -->
<div class="content">
    <div class="France all">...</div>
    <div class="Canada all">...</div>
    <div class="Portugal all">...</div>
</div>

jQuery

$(document).ready(function(){

    $("#France").click(function(){
            $(".all").hide();
            $(".France").show();                
    }); 

    $("#Canada").click(function(){
            $(".all").hide();
            $(".Canada").show("");
            }); 

    $("#Portugal").click(function(){
            $(".all").hide();
            $(".Portugal").show("");        
    }); 

});     

【问题讨论】:

  • 非常感谢所有出色的解决方案

标签: jquery show-hide


【解决方案1】:

是的,你可以这样做:

$('.nav span').click(function(){
    $('.all').hide();
    $('.'+this.id).show();
});

Demonstration

【讨论】:

    【解决方案2】:

    你可以带走类all,使用.siblings().hide()

    $('.nav span').click(function(){
        $('.'+this.id).show("").siblings().hide("");
    });​
    

    【讨论】:

      【解决方案3】:
      $('.nav span').on('click', function() {
          $('.content > div').eq($(this).index()).toggle().siblings().hide();
      });​
      

      FIDDLE

      【讨论】:

        【解决方案4】:

        您可以跟踪显示的内容:

        $(document).ready(function(){
        
            var $current,
                $contents = $('.content .all').hide();
        
            $('.nav span').click(function() {
                if ($current) {
                    $current.hide();
                }
                $current = $contents.filter('.' + this.id).show();
            });
        }); ​
        

        【讨论】:

          猜你喜欢
          • 2023-01-03
          • 1970-01-01
          • 2015-04-29
          • 2011-02-22
          • 2012-04-15
          • 2011-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多