如果所有子代均已分配课程,则选择父节点 [英] select parent node if all children have assigned class

查看:147
本文介绍了如果所有子代均已分配课程,则选择父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种遍历无序列表的有效方法,该列表包含多个包含.selected类的级别.如果组中的所有UL LI都具有.selected类,则需要添加.selected类,以作为子UL的父级LI.

I am looking for an efficient way to traverse a unordered list which contains multiple levels which contain the class .selected. If all the UL LI in a group have the class .selected, I need to add the class .selected the parent LI of the child UL.

<ul>
    <li>one <-- this li adds class .selected if ALL its children have .selected
        <ul>
            <li class="selected">red</li>
            <li class="selected">green</li>
            <li class="selected">blue</li>
        </ul>
    </li>
    <li>two
        <ul>
            <li class="selected">red</li>
            <li>green</li>
            <li class="selected">blue</li>
        </ul>
    </li>
    <li>three</li>
</ul>

如果任何给定UL中的所有子级都具有.selected类,则将该类.select添加到父级LI中,因此在这种情况下,包含文本"one"的LI将是唯一拥有.selected类的父级LI.添加.

if ALL the children in any given UL have the class .selected add the class .selected to the parent LI, so in this case the LI containing the text "one" would be the only parent LI to have the class .selected added.

我需要在页面加载时发生这种情况.并且我尝试了很多方法,但是这个方法最接近,但是我不确定它是否最有效:

I need this to happen when the page loads. and I have tried a bunch of methods but this one came closest but I am not too sure if its the most efficient:

$("ul li").filter(function () {
    var lis_total = $(this).siblings().length + 1;
    var lis_selected = $(".selected", this).siblings().length + 1;
    if(lis_total == lis_selected)
        return $(this).parent("li").addClass("selected");
});

我不太确定我是否做得正确.它不起作用.

I am not too sure if I am doing it correctly. Its not working.

推荐答案

如果您想要单线,请尝试 http: //jsfiddle.net/4JNaL/

if you want a one-liner, try http://jsfiddle.net/4JNaL/

$('li ul:not(:has(li:not(.selected)))').parent().addClass('selected');

var theParent = $('li ul:not(:has(li:not(.selected)))').parent();

返回要操作的元素

对于任意深度的树: http://jsfiddle.net/GQbmU/4/

do {
    $results = $('li:not(.selected) > ul:not(:has(li:not(.selected)))');
    $results.parent().addClass('selected');
} while ( $results.length > 0);

或者,因为此答案的主题是单线的: http://jsfiddle.net/GQbmU/6/

or, since the theme of this answer is one-liners: http://jsfiddle.net/GQbmU/6/

while ( $('li:not(.selected) > ul:not(:has(li:not(.selected)))').parent().addClass('selected').length > 0) {} ;

这篇关于如果所有子代均已分配课程,则选择父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆