开发者

addClass if ul exists (jQuery)

I'm building a simple drop开发者_如何学Pythondown where I'd like to add a class to parent if UL exists:

HTML:

<ul id="menu">
  <li><a href="#">Parent 1</a></li>
  <li><a href="#">Parent 2</a>
    <ul>
      <li><a href="#">Sub 2.1</a></li>
      <li><a href="#">Sub 2.2</a></li>
    </ul>
  </li>
</ul>

So I'd like to:

  • hide all nested (ul#menu > li > ul) ul's initially
  • show/hide nested ul on hover
  • addClass "dropdown" to parents that have nested ul's

This isn't quite working, not sure why:

$(function () {
    $("ul#menu li").hover(function () {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');
    },
    function () {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
    });
    $("ul#menu li ul li:has(ul)").find("a:first").addClass("dropdown");
});

Many thanks for your help!


var ul = $('#menu');

if (ul.length) {
    ul.children('li').hover(function() {
        $(this).children('ul').show();
    }, function() {
        $(this).children('ul').hide();
    }).children('ul').hide().parent().addClass('dropdown');
}

Demo: http://jsbin.com/ofayu

BTW: you are closing the <li> tags incorrectly in your markup.


You wrote:

$("ul#menu li ul li:has(ul)")

Given your HTML structure, shouldn't this be:

$("ul#menu li:has(ul)")


This should do the trick (untested):

$('ul#menu > li > ul').each(function()
{
    var list = $(this);
    list.hide();
    list.parent().hover(list.hide, list.show);
    list.parent().parent().addClass('dropdown');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜