1

Hello Fellas i am trying to use nth-child in my code but its not working following is my code

HTML

<ul class="colour" >
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>one</li>
    <li>two</li>
    <li>three</li>
  </ul>

jQuery

$(document).ready(function(e) {
    $('.colour ul li:nth-first-child(1)').css('color','pink');
});

I don't know why its not working plz help guys

4

4 回答 4

3

nth-first-child is not a pseudo-selector, nth-child is.

You're also selecting .colour ul which looks for a ul that is a descendant of an element with the class .colour. That won't work with your markup. You'd want just .colour or ul.colour.

Demo

In response to your comment, you'd want to use nth-last-child in that scenario, which does exist. Demo

于 2013-04-11T07:29:06.017 回答
1

除了上面已经很棒的答案之外,eq如果这些li项目的数量保持不变,您还可以使用 。

<ul class="color">
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

和 JS:

//The indexing starts from 0, like in arrays
$('.color li:eq(0)').css('color', 'pink');

因此,倒数第二个可以访问为:

$('.color li:eq(5)').css('color', 'pink');

只是我的2美分!

于 2013-04-11T14:15:18.330 回答
1

您应该使用以下内容:

$(document).ready(function(e) {
    $('.colour ul li:nth-last-of-type(2)').css('color','pink');
});

这将选择倒数第二个元素。这是更多教程。

于 2013-04-11T07:35:18.753 回答
0

如果要对倒数第二个进行风格化<li>,可以使用:

$(document).ready(function(e) {
    $('.colour li:nth-last-child(2)').css('color','pink');
});

Working Demo

于 2013-04-11T07:33:13.813 回答