我有一个类的 div 负载,testimonial我想使用 jquery 循环遍历它们以检查每个 div 是否特定条件为真。如果是真的,它应该执行一个动作。
有谁知道我会怎么做?
我有一个类的 div 负载,testimonial我想使用 jquery 循环遍历它们以检查每个 div 是否特定条件为真。如果是真的,它应该执行一个动作。
有谁知道我会怎么做?
使用每个: ' i' 是数组中的位置,obj是您正在迭代的 DOM 对象(也可以通过 jQuery 包装器访问$(this))。
$('.testimonial').each(function(i, obj) {
    //test
});
查看api 参考以获取更多信息。
试试这个...
$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...
    if(condition){
    }
 });
现在不用 jQuery 就可以很简单地做到这一点。
只需选择元素并使用该.forEach()方法迭代它们:
const elements = document.querySelectorAll('.testimonial');
Array.from(elements).forEach((element, index) => {
  // conditional logic here.. access element
});
在旧浏览器中:
var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(element, index) {
  // conditional logic here.. access element
});
试试这个例子
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>
当我们想访问那些divs具有data-index大于2那么我们就需要这个jQuery。
$('div[class="testimonial"]').each(function(index,item){
    if(parseInt($(item).data('index'))>2){
        $(item).html('Testimonial '+(index+1)+' by each loop');
    }
});
你可以这样做
$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});