这是 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';
});
或者,在那些不支持 previousElementSibling
的浏览器中工作:
$('p').addClass(function(){
return !$(this).prev().length ? 'first' : 'notfirst';
});
引用资料:
关于javascript - 检查 <p> 是否是第一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17196484/