如何改进我的jQuery显示/隐藏实现



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

该目录

<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("");        
    }); 
});     

是的,你可以这样做:

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

示范

你可以拿走类all并使用.siblings().hide()

$('.nav span').click(function(){
    $('.'+this.id).show("").siblings().hide("");
});​
$('.nav span').on('click', function() {
    $('.content > div').eq($(this).index()).toggle().siblings().hide();
});​

小提琴

您可以跟踪显示的内容:

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

最新更新