最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery Slidetoggle, how to allow to show only one element? - Stack Overflow

programmeradmin1浏览0评论

This is my html:

<ul>
    <li>
        List
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
            <li>Item 5</li>
        </ul>
    </li>

    <li>
        List 2
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </li>
</ul>

And this js:

$('ul li ul').hide();

$('ul li').click(function() {
    $(this).children().slideToggle();
});

I want to create slidetoggle, for example: when user click "List" and after open this user click List 2 then list one is hiding.

DEMO: / I want only one open when user click.

Thanks!

This is my html:

<ul>
    <li>
        List
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
            <li>Item 5</li>
        </ul>
    </li>

    <li>
        List 2
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </li>
</ul>

And this js:

$('ul li ul').hide();

$('ul li').click(function() {
    $(this).children().slideToggle();
});

I want to create slidetoggle, for example: when user click "List" and after open this user click List 2 then list one is hiding.

DEMO: http://jsfiddle/7dxAb/ I want only one open when user click.

Thanks!

Share Improve this question asked May 29, 2014 at 21:28 user3501587user3501587 4255 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Try this:

$('ul li ul').hide();

$('ul li').click(function() {
    var _this = $(this);
    _this.children().slideToggle();

    $('ul > li').not(_this).children('ul').slideUp();
});

You hide "ul"s in all ListN elements except one that is clicked.

You can slideUp() all the other ul's before the slideToggle() like this:

$('ul li').click(function() {
    $(this).parent().find('ul').slideUp();
    $(this).children().slideToggle();
});

I'm not sure if this is the most effecient way tho.

Add

$('ul li ul').slideUp();

to the click event. This will hide the other uls. The finished code would look like:

$('ul li ul').hide();

$('ul li').click(function() {
    $('ul li ul').slideUp();
    $(this).children().slideToggle();
});

http://jsfiddle/yvPFx/2/

Edit: You can use a class to keep track of what is showing. http://jsfiddle/yvPFx/3/

Try this:

 $('ul li ul').hide();

 $("ul li").click(function () {
     $(this).children().slideToggle("slow", function() {
        //
      });
     $(this).siblings().children().slideUp("slow");
 });
发布评论

评论列表(0)

  1. 暂无评论