简单的第一个孩子没有按预期工作

时间:2014-01-06 12:59:37

标签: jquery html css

我以为我理解这一点,但显然不是。

http://jsfiddle.net/tmyie/w6nMe/2/

$('p:first-child').css({color:'red'});

不会更改任何文字的颜色。

<div class="post text"> <a href="#">this is a url</a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
</div>
<div class="post text"> <a href="#">this is a url</a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
</div>

7 个答案:

答案 0 :(得分:2)

我认为你在寻找:

$('p:first').css({color:'red'});

更新:

<p>

上选择第一个<div>
$('div p:first-of-type').css({color:'red'});

Live Demo

答案 1 :(得分:2)

应该是

$('p:first').css({color:'red'});

更改

p:first-child {
    background-color: orange;
}

p:first-of-type {
    background-color: orange;
}

Updated fiddle here.

答案 2 :(得分:0)

尝试 :first :eq(0)

$('p:first').css({color:'red'});

DemoEq demo

答案 3 :(得分:0)

我认为您正在尝试选择每个父帖子的第一个p标签子项,这是我的解决方案:

$('div.post p:first-child').css({color:'red'})

答案 4 :(得分:0)

尝试此代码:

$(function() {
  $("p:first").addClass("first");
});

css:p.first { color: red; }

答案 5 :(得分:0)

在css中:first-child选择器用于选择指定的选择器,只有它是其父节点的第一个子节点。

<强> fiddle

<强> CSS

p:first-child {
    background-color: orange;
}

答案 6 :(得分:0)

这是一种黑客行为。您可以在jquery中包含以下内容。

$('p:nth-child(2)').css({color:'red'});