开发者

Jquery collapsible region

I am trying to make sections of page collapsible. No plan to use accordion, but simple hide/show to save screen space. See the sample code below. The first link has to click twice to make the section hide, and the second one works fine. Neglect this issue, if you can suggest a better way to do it.. In this example, div1 is in open position and div2 hidden initially.

thanks, bsr.


<!doctype html>
<head>
        <script type="text/javascript" src="http://ajax.goo开发者_StackOverflowgleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>

<body>

<a class="toggle" href="#">Hide</a>
<div class="toggle">
    <p>First div</p>
</div>

<a class="toggle" href="#">Show</a>
<div class="toggle" style="display: none">
    <p>Second div</p>
</div>


<script type="text/javascript">
jQuery().ready(function() {
    $("a.toggle").toggle( 
        function() {
            $(this).text("Hide");
            $(this).next("div.toggle").show();
        },
        function() { 
            $(this).text("Show");
            $(this).next("div.toggle").hide();
        } 
    );  
});  
</script>
</body>
</html>


I would use the toggle() function, as it's not only used to bind toggling events, it also toggles visibility is called without any parameters:

jQuery().ready(function() {
    $("a.toggle").click(function(){
        var $div = $(this).next("div.toggle");
        $div.toggle();
        if($div.is(':visible'))
            $(this).text('Hide');
        else
            $(this).text('Show');
    });
});

The problem with your code is that you're showing/hiding the elements regardless of their initial state. No matter what you do, if you bind events using toggle(func, func), the first function will always be called first.


The reason the first one needs to be clicked twice is because it starts with the div showing. When you click on it the first time, because of the nature of the toggle event, jQuery thinks that you're trying to show it. But it's already showing. So none of the changes take effect.

You can solve this by having everything start out hidden. But if that's not an option, then you'll have to do away with the toggle event listeners and just listen for clicks:

$('a.toggle').click(function () {
    var $this = $(this);
    if ($this.text() === 'Show') {
        $this.text('Hide').next('div.toggle').show();
    } else {
        $this.text('Show').next('div.toggle').hide();
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜