我有一个div与类的证明,我想用jquery循环通过他们检查每个div如果一个特定的条件是真的负载。如果为真,它应该执行一个操作。

有人知道我会怎么做吗?


当前回答

试试这个…

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });

其他回答

jQuery的.eq()可以帮助您使用索引方法遍历元素。

var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
    var element = testimonialElements.eq(i);
    //do something with element
}

你可以这样做

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});

试试这个…

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });

现在不使用jQuery也能很简单地做到这一点。

没有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>

当我们想要访问那些数据索引大于2的div时,我们需要这个jquery。

$('div[class="testimonial"]').each(function(index,item){
    if(parseInt($(item).data('index'))>2){
        $(item).html('Testimonial '+(index+1)+' by each loop');
    }
});

工作实例小提琴