简体   繁体   English

使用jQuery选择器选择有子项而不是子项的项目

[英]Selecting items with children but not grandchildren using jQuery selectors

I am trying to select list items that have children, but not list items that are grandchildren. 我试图选择具有子项的列表项,而不是具有孙子项的列表项。 Consider the following structure: 考虑以下结构:

<ul id="parent">
   <li>
      <a href="#"></a>
      <ul> <!-- add open class -->
        <li><a href="#"></a></li>
        <li>
            <a href="#"></a>
            <ul>  <!-- do not add any class -->
                <li><a href="#"></a></li>
            </ul>
        </li>
      </ul>
   <li>
</ul>

I hide all children lists like so: 我像这样隐藏所有子列表:

#parent li > ul {display:none}

When I hover over any top-level list item, I would like to add a class to its child <ul> but NOT its grandchild <ul> . 当我将鼠标悬停在任何顶级列表项上时,我想向其子级<ul>添加一个类,但不为其孙级<ul>添加一个类。 So in the tree above I wrote the <ul> that needs a class added. 因此,在上面的树中,我写了<ul> ,需要添加一个类。

The following selects all list items with children: 以下选择带有子项的所有列表项:

$("#parent li:has(ul)").hoverIntent( showSubNav, hideSubNav );

I need this to ONLY select the top level list items that HAVE children but I do not want this function to trigger when I hover over grandchildren list items that also have children. 我只需要选择拥有孩子的顶级列表项,但是当我将鼠标悬停在也有孩子的孙列表项上时,我不希望此功能触发。

How can I accomplish this? 我该怎么做?

Use a descendent selector. 使用后代选择器。

$("#parent > li:has(ul)").hoverIntent( showSubNav, hideSubNav );

This will only do $.hoverIntent() on immediate children li s that have a child ul . 这只会做$.hoverIntent()眼前的孩子li有一个孩子的ul

If you want to show the adjacent ul when you hover over the <a> , then this: 如果要在将鼠标悬停在<a>时显示相邻的ul ,请执行以下操作:

$('#parent > li > a').hover(function() {
    $(this).next('ul').addClass();
});

Hovering over a top level <li> and then add a class to it's immediate <ul> child: 将鼠标悬停在顶级<li> ,然后向其直接的<ul>子级添加一个类:

$('#parent > li').hover(function() {
    $(this).child('ul').addClass();
});

would this work? 这会工作吗?

//find the first UL in #parent
$('#parent').find('ul').first().each(function(){
    //check if the first UL has any children
    if($(this).find('ul').length > 0){
        //this ul has children UL
    }
    else{
        //this does not have children UL
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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