gpt4 book ai didi

javascript - 检查

是否是第一个 child

转载 作者:搜寻专家 更新时间:2023-11-01 05:05:49 25 4
gpt4 key购买 nike

这是 jsfiddle 上的代码 http://jsfiddle.net/KGDyR/

我需要在(每个)div 中的(每个)p 上添加类

如果 p 是 div 标签的第一个 child ,添加类 .first

如果不加.notfirst

所以输出会是这样

<div>
<p class="first">p is first</p>
<img src="http://projectfoo.com/images/foo_logo.gif" />
</div>

<div>
<img src="http://projectfoo.com/images/foo_logo.gif" />
<p class="notfirst">p is not first</p>
</div>

最佳答案

为了简单起见,我建议:

$('p').addClass(function(){
return this.previousElementSibling === null ? 'first' : 'notfirst';
});

JS Fiddle demo .

或者,在那些不支持 previousElementSibling 的浏览器中工作:

$('p').addClass(function(){
return !$(this).prev().length ? 'first' : 'notfirst';
});

JS Fiddle demo .

引用资料:

关于javascript - 检查 <p> 是否是第一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17196484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com