简体   繁体   中英

Jquery + select the first ul of a menu

I have read several posts of this problem but I don't find the solution.

I have created a menu with 3 levels. I want to display the second & the third levels with a hover on the first level. For this I use the code:

$("#header ul.menu li").hover(
    function(){
        $(this).find("ul").fadeTo('slow', 0.9);
    },
    function(){
        $(this).find("ul").fadeOut('slow');
    }
);

It's ok and the submenu appears with a hover on the first level.

But, if I make a hover the second and the third level some ul children of the first ul, disappears.

How can I select only the first ul in my function? I have tried with several methods but without success :

$("#header ul.menu > li").hover(...

or

$(this).children("ul")....

Can you help me to resolve this problem?

Thanks for your replies.

Have you tried using the :eq pseudo selector? http://api.jquery.com/eq-selector/

You can select any element using an index:

$('a:eq(0)')

The above will return the first <a> element on the page.

I have used the following method, it is working fine for me.

  $("ul.menu > li").hover(
            function(){
                $(this).find("ul").fadeTo('slow', 0.9);
            },
            function(){
                $(this).find("ul").fadeOut('slow');
            }
        );

FIDDLE DEMO

I have found a solution, but it may not be clean. With JQuery, I add a class on the first ul.menu (nav). Then I write this code:

            $(".menu-parent-wrapper > ul").addClass("nav");
            $("#header ul.nav > li").hover(
                function(){
                    $(this).find("ul").fadeTo('slow', 0.9);
                },
                function(){
                    $(this).find("ul").fadeOut('slow');
                }
            );

Now the menu is ok. The third level don't disapears when I make a hover on the items of the second level.

If you have another solution, you can post a new message.

Thanks.

This JSFiddle seems to do what you want.

I'm using jQuery's children() instead of find() as this prevents the secondary menus from being shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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