1

给定以下无序的嵌套列表结构:

<ul id="nestedList">
    <li>
        Item A
        <ul>
            <li>Item A Descrip</li>
        </ul>
    </li>
    <li>
        Item B
        <ul>
            <li>Item B Descrip</li>
        </ul>
    </li>
    <li>
        Item C
        <ul>
            <li>Item C Descrip</li>
        </ul>
    </li>
</ul>

我需要使用什么 jQuery 选择器来设置顶级 li 元素(项目 A、项目 B 等)而不是“描述”li 元素的样式?

我尝试使用 .children() 选择器,jQuery 文档说它只选择所选元素的直接子元素,但我尝试的所有内容要么设置整个列表的样式,要么只设置二级 li 元素的样式。

这是我正在使用的 jQuery:

$('#nestedList').children().css('font-weight', 'bold');

和:

$('ul#nestedList').children().css('font-weight', 'bold');

更新 我为此创建了一个jsFiddle,所以随意弄乱它......

4

4 回答 4

4

“但我尝试的所有东西都设置了整个列表的样式”

这是因为您放置在顶层的样式是从顶层的样式继承的。

您需要覆盖嵌套列表中的这些样式。

$('#nestedList').children().css('font-weight', 'bold')
                .find('li').css('font-weight','normal');

工作示例:http: //jsfiddle.net/w66rK/

于 2011-07-20T16:37:26.463 回答
1

试试这个

$('#nestedList > li').css('font-weight', 'bold');
于 2011-07-20T16:33:28.867 回答
0
$('#nestedList > li') 

http://api.jquery.com/child-selector/

于 2011-07-20T16:33:39.900 回答
0

使用直接 CSS 将是最简单的:

#nestedList > li {
    /* direct li descendants of the parent ul */
    /* CSS */
}

当然,同样的选择器也适用于 jQuery:

$('#nestedList > li').css('color','red'); // etc...
于 2011-07-20T16:33:40.667 回答