简体   繁体   中英

Select All except Parents in Jquery

I Have Following codes:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $("#ThisClick").anycommand();
    </script>
</head>
<body>
<ul id="TopUl">
    <li>First<ul>
        <li>One<ul>
            <li>liA1</li>
            <li>liA2</li>
        </ul>
        </li>
        <li>Two<ul>
            <li id="ThisClick">liB1</li>
            <li>liB2</li>
        </ul>
        </li>
    </ul>
    </li>
    <li>Second<ul>
        <li>li1<ul>
            <li>liF1</li>
            <li>liF2</li>
        </ul>
        </li>
        <li>li2</li>
    </ul>
    </li>
</ul>
</body>
</html>

I need collaps all UL's that are not parents of liB1 (#ThisClick) when clicking. In other words by click on liB1 I want have following code:

<ul id="TopUl">
    <li>First<ul>
        <li>One<ul style="display:none">
            <li>liA1</li>
            <li>liA2</li>
        </ul>
        </li>
        <li>Two<ul>
            <li id="ThisClick">liB1</li>
            <li>liB2</li>
        </ul>
        </li>
    </ul>
    </li>
    <li>Second<ul style="display:none">
        <li>li1<ul style="display:none">
            <li>liF1</li>
            <li>liF2</li>
        </ul>
        </li>
        <li>li2</li>
    </ul>
    </li>
</ul>

Then Jquery may collapse all not parented UL tags. What is the solution? how can I do for this propose?

This icky looking selector should work:

$("ul :not(:has(#ThisClick))").hide();

References: :not() and :has()


So, this bit of code will make all the elements that are not parents of the element you clicked, hide. Change the first selector ( $("#ThisClick") ) as needed, right now it only works on the <li> that you've specified the ThisClick ID on, and you can only use an ID once.

$("#ThisClick").click(function() {
    $("ul :not(:has(this))").hide();
});

To make this work on all <li> s that are in your <ul> , you could do this:

$("#TopUl li").click(function() {
    $("ul :not(:has(this))").hide();
});

This adds the click event to all <li> s in your list.

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