我有一个div与类的证明,我想用jquery循环通过他们检查每个div如果一个特定的条件是真的负载。如果为真,它应该执行一个操作。
有人知道我会怎么做吗?
我有一个div与类的证明,我想用jquery循环通过他们检查每个div如果一个特定的条件是真的负载。如果为真,它应该执行一个操作。
有人知道我会怎么做吗?
当前回答
试试这个例子
Html
<div class="testimonial" data-index="1">
Testimonial 1
</div>
<div class="testimonial" data-index="2">
Testimonial 2
</div>
<div class="testimonial" data-index="3">
Testimonial 3
</div>
<div class="testimonial" data-index="4">
Testimonial 4
</div>
<div class="testimonial" data-index="5">
Testimonial 5
</div>
当我们想要访问那些数据索引大于2的div时,我们需要这个jquery。
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
工作实例小提琴
其他回答
我可能忽略了部分问题,但我相信你可以简单地这样做:
$('.testimonial').each((index, element) => {
if (/* Condition */) {
// Do Something
}
});
这使用jQuery的每个方法:https://learn.jquery.com/using-jquery-core/iterating/
divs = $('.testimonial')
for(ind in divs){
div = divs[ind];
//do whatever you want
}
使用简单的for循环:
var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
// Using $() to re-wrap the element.
$(testimonials[i]).text('a');
}
你可以使用jQuery $each方法循环遍历所有的元素与类凭据。 I =>是集合中元素的索引,val给你特定元素的对象,你可以使用“val”来进一步访问元素的属性并检查你的条件。
$.each($('.testimonal'), function(i, val) {
if(your condition){
//your action
}
});
更精确的:
$.each($('.testimonal'), function(index, value) {
console.log(index + ':' + value);
});