开发者

jQuery tree menu

开发者 https://www.devze.com 2023-02-04 22:18 出处:网络
I\'m doing a tree view menu, the html is something like this: <ul id=\"sec1\"> <li> 开发者_运维问答 <a href=\"\">First</a>

I'm doing a tree view menu, the html is something like this:

<ul id="sec1">

    <li>
       开发者_运维问答 <a href="">First</a>

        <ul id="sec2">

            <li>
                <a href="">aaaa</a>

                <ul id="sec3">

                    <li><a href="">1</a></li>
                    <li><a href="">2</a></li>

                </ul>

            </li>


            <li><a href="">bbbb</a></li>

        </ul>

    </li>

    <li><a href="">Second</a></li>

    <li><a href="">Third</a></li>

</ul>

All that I need is:

when someone click on the first child it open ONLY the second child of the relative link.

If another second child is open I would like that it close when I click another one.

Same must work on second child... there are three steps: ul#sec1, ul#sec2 and the last one ul#sec3.

the jQuery code that I'm using is this:

var sec1 = $('ul.sec1 li a');

    sec1.each(function () {

        var secc1 = $(this)

        secc1.click(function () {
            $(this).parent().find('ul').slideToggle();
            return false;
        });

    });

Everything work fine but:

if another child is open and I click on another one it doesn't close.

When I expand one child, inside all the other sub-child are open...

Can someone help me perform that, I'm gonna be crazy!

Thanks


If you use the next() function it will get ONLY the ul after the a that was clicked.

$(function ()
{
    $('#sec1 li a').each(function ()
    {
        $(this).click(function (event)
        {
            event.preventDefault(); // Prevents the browser to navigate to the specified url (href)

            // Close all other ul's excluding the ul's in the current branch.
            $("#sec1 ul").not($(this).next()).not($(this).parentsUntil("#sec1")).slideUp();

            $(this).next().slideToggle(); // Toggle the targeted ul
        });
    });
});

Edit:
Added code that closes the other ul's except the ones in the current branch.


Both the lines will find the same element, and there will be a race condition between the slides. Remember that the effects are an asynchronous operation. It is best to put the second line as a callback on success of the first line.

I can't give you code here because I don't understand the DOM hierarchy you want to maintain. If you want a treeview, consider jsTree. I love it!

0

精彩评论

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