繁体   English   中英

有关如何更新导航代码以隐藏和显示隐藏div的建议

[英]Advice on how to update navigation code to hide and show hidden div

我目前有一个列表,其中包含一个隐藏/显示隐藏div的特定链接。 单击链接时,将删除并添加“活动”类,并检查隐藏的div以查看它是可见还是隐藏,并相应地隐藏/显示。 一切正常,但是,有一个问题。 当我点击Square我想要显示#square但是当我再次点击它时我想隐藏#square但是因为我正在检查.active这个不能完成。 任何人都可以提供有关如何更新代码的任何建议,以便实现这一目标吗?

JS

$(document).ready(function(){

    var square = $('#square'),
        test = $('#test');

    square.hide();

    test.find('a').on('click', function(e){

        if( !$(this).hasClass('active') ){


            if ( square.is(':visible') ){
              square.hide();
            }

            var id = $(this).data('id');

            test.find('a').removeClass('active');
            $(this).addClass('active');

            if( id === 'square' ){
              square.show();
            }

        }

        e.preventDefault();
    });        

});​

HTML

<ul id="test">
<li><a href="#">Triangle</a></li>
<li><a href="#" data-id="square">Square</a></li>
<li><a href="#">Circle</a></li>
</ul>

<div id="square"></div>​

小提琴: http//jsfiddle.net/xBuUY/

移动这段代码 - if(square.is(':visible')){square.hide(); 在hasClass('active')之外检查。

你的逻辑可以简化,你想要切换square而不管类,所以我已经删除了类测试之外的square切换。 这里尝试这个小提琴

我做你小提琴的叉子 我已经移动了块来测试方块是否应该可见而不是检查哪个链接应该是活动的。 #square被切换,不仅显示了它已经处于活动状态时隐藏的#square 试试小提琴。

除此之外,我优化了事件处理程序:它现在使用委托,这比每个链接上的链接处理程序更快。 e.stopPropagation()阻止了链接的冒泡。 我已经在任何其他方法之前添加了这个,或者出于性能原因调用了其他任何方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM