开发者

What am I doing wrong for this submenu to not appear?

开发者 https://www.devze.com 2022-12-28 02:06 出处:网络
I\'m new to jQuery, so please bear with me. I\'m trying to make my submenu appear on hover. The second set of <ul> is for submenu.

I'm new to jQuery, so please bear with me. I'm trying to make my submenu appear on hover. The second set of <ul> is for submenu.

$(document).ready(function(){
    $('ul.menu.li').hover(
        function() { $('ul', this).css('display', 'block'); },
     开发者_Python百科   function() { $('ul', this).css('display', 'none'); });
});

<ul id="menu">
<li><a href="#">Item 1</a><li>
<ul>
<li>Hi</li>
</ul>
<li><a href="#">Item 2</a></li>
</ul>


Your selector is wrong. You need to reference the parent UL by ID, not class:

$('#menu li').hover(...

moreover, if you are addressing LIs within the UL, you want to use either ancestor-descendant or parent > child:

$('#menu li') // ancestor descendant
$('#menu > li') // parent > child

Additionally, there is no point in setting the CSS display property, when you can just:

$(document).ready(function(){
    $('#menu li').hover(
        function() { $('ul', this).show(); },
        function() { $('ul', this).hide(); });
});


There's a few things here, first the selector should be ul#menu li since menu is the id not the class (class selectors use .class). Also a space in there, otherwise it's looking for a <ul> with a class="menu li" to match.

Then, your <ul> needs to be a child of the <li> not a sibling, like this:

<ul id="menu">
<li><a href="#">Item 1</a>
    <ul>
    <li>Hi</li>
    </ul>
</li>
<li><a href="#">Item 2</a></li>
</ul>​

Lastly, you can add a bit of flair as well, like this:

$('ul#menu li').hover(function() { 
    $('ul', this).slideDown(); 
}, function() {
    $('ul', this).slideUp(); 
});​

This creates a sliding effect as well that you can see here

0

精彩评论

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