我有这段代码:
$(".feed-item .field-content p").each(function(i) {
$(this).addClass("item" + (i+1));
});
此代码帮助我在此标记内的段落中添加类:
<div class="feed-item">
<div class="field-content">
<p>This must be class item1</p>
<p>This must be class item2</p>
</div>
</div>
<div class="feed-item">
<div class="field-content">
<p>This must be class item1</p>
<p>This must be class item2</p>
</div>
</div>
但是我需要总是从数字1开始计数。我解释得好吗?现在我得到了这个结果:
<div class="feed-item">
<div class="field-content">
<p class="item1">This must be class item1</p>
<p class="item2">This must be class item2</p>
</div>
</div>
<div class="feed-item">
<div class="field-content">
<p class="item3">This must be class item1</p>
<p class="item4">This must be class item2</p>
</div>
</div>
这就是我需要的(注意区别在于与第二个field-content div中的p标签相关的类):
<div class="feed-item">
<div class="field-content">
<p class="item1">This must be class item1</p>
<p class="item2">This must be class item2</p>
</div>
</div>
<div class="feed-item">
<div class="field-content">
<p class="item1">This must be class item1</p>
<p class="item2">This must be class item2</p>
</div>
</div>
我正在处理此链接:http://jsfiddle.net/bosspetta/RJkP5/
答案 0 :(得分:5)
您可以将函数传递给addClass
方法:
$(".feed-item .field-content").each(function() {
$('p', this).addClass(function(i){
return "item" + ++i
});
});