简体   繁体   English

jQuery儿童方法选择孙子

[英]jQuery children method selecting grandchildren

I was following tutorial on net.tuts on jQuery. 我正在关注有关jQuery的net.tuts的教程。 I am having problem with jQuery children selection method. 我在使用jQuery儿童选择方法时遇到问题。 My understanding with the following function I could change color of the children but it goes more than one level down to change color of all list elements to red. 我对以下功能的理解是,我可以更改子级的颜色,但是它将所有列表元素的颜色都更改为红色不只一层。 What did I do wrong? 我做错了什么? I have seen the same script work fine on the video tutorial. 我在视频教程中看到相同的脚本可以正常工作。 Here is the code 这是代码

<ul class="color_change">
    <li>Item 1</li>
    <li>Item 2</li>
    <li> 
        <ul>
            <li>sub item</li>
            <li>sub item</li>
        </ul>
    </li>
</ul>

<script>
    $('ul.color_change').children('li').css('color','red');
</script>`

You could use that: 您可以使用:

DEMO DEMO

$('ul.color_change').children('li').not(':has(ul)').css('color','red');

An other way which will set red color for all first level children: 另一种为所有一级孩子设置红色的方法:

DEMO 2 演示2

$('ul.color_change').find('ul').css('color','black').end().children('li').css('color','red');

But better would be to just use CSS rules: 但是更好的方法是只使用CSS规则:

DEMO 3 演示3

ul.color_change > li{color:red}
ul.color_change > li > ul{color:black}

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

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