简体   繁体   English

使用jQuery选择所有子代和子代

[英]Selecting all children and decendants with jQuery

I have some HTML that is being produced by a WordPress plugin that is designed to allow for expandable/collapsible text, with up to three levels of depth. 我有一些由WordPress插件生成的HTML,该HTML插件旨在允许可扩展/可折叠的文本,其深度最多为三个级别。 I would like it so that if you were to collapse the first or second levels and the children below it were also expanded those too would get collapsed but nothing I use seems to allow the selection of all children. 我想这样,如果您要折叠第一层或第二层,并且下面的孩子也要展开,那么那些孩子也将崩溃,但是我所使用的似乎不允许所有孩子的选择。 This is what I'm using so far: 到目前为止,这是我正在使用的:

$(".hidden-text-toggle").click(function () {
    if ($(".hidden-text:animated").length) return false;
        $(this).next().slideToggle();
        if ($(this).hasClass('expanded') ){     
            $(this).removeClass('expanded');
            $(this).animate({ backgroundColor: "black" , color: "red"});    
        }
        else
        {
            $(this).addClass('expanded');
            $(this).animate({backgroundColor: "red" , color: "black"});

        }
        return false;
    });

<div class="wrapper">
    <h2 class="title">Level One</h2>
    <div class="text" href="#">
        This is level one text.
        <div class="wrapper">
            <h2 class="title" href="#">Level Two</h2>
            <div class="text">
                This is level two text.
                <div class="wrapper">
                    <h2 class="title" href="#">Level Three</h2>
                    <div class="text">                          
                        This is level three text. 
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

I would have thought that putting something like $(this).find(".text").slideUp(); 我本以为放像$(this).find(".text").slideUp(); after line 4 would allow this but apparently I am wrong. 第4行之后将允许这样做,但显然我错了。

Any help would be much appreciated! 任何帮助将非常感激!

You can just do a blanket slideUp on every element (do this in combination with find ): 您可以在每个元素上进行通用的slideUp (与find结合使用):

$("div.wrapper").find("div").slideUp();

Note that this is essentially selecting every div underneath the root node, then animating the height of each to zero. 请注意,这实际上是选择根节点下的每个div ,然后将每个高度的动画设置为零。 Any elements that are already zero height will not be affected. 高度已经为零的任何元素都不会受到影响。

Try: 尝试:

$("h2.title").click(function () {
    $(this).next().slideToggle();
});​

Fiddle: http://jsfiddle.net/iambriansreed/amppK/ 小提琴: http : //jsfiddle.net/iambriansreed/amppK/

Docs: http://api.jquery.com/toggle-event/ 文件: http//api.jquery.com/toggle-event/

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

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