本文翻译自:jQuery to loop through elements with the same class
I have a load of divs with the class testimonial
and I want to use jquery to loop through them to check for each div if a specific condition is true. 我有一个带有类testimonial
的div的加载,我想使用jquery循环遍历它们以检查每个div,如果特定条件为真。 If it is true, it should perform an action. 如果是,它应该执行一个动作。
Does anyone know how I would do this? 有谁知道我会怎么做?
参考:https://stackoom.com/question/JrsU/jQuery循环使用相同类的元素
jQuery's .eq() can help you traverse through elements with an indexed approach. jQuery的.eq()可以帮助您使用索引方法遍历元素。
var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
var element = testimonialElements.eq(i);
//do something with element
}
It's pretty simple to do this without jQuery these days. 这些天没有jQuery这样做很简单。
Just select the elements and use the .forEach()
method to iterate over them: 只需选择元素并使用.forEach()
方法迭代它们:
var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(elements, index) {
// conditional here.. access elements
});
Try this example 试试这个例子
Html 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>
When we want to access those divs
which has data-index
greater than 2
then we need this jquery. 当我们想要访问data-index
大于2
那些divs
,我们需要这个jquery。
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
Working example fiddle 工作范例小提琴
More precise: 更确切:
$.each($('.testimonal'), function(index, value) {
console.log(index + ':' + value);
});
With a simple for loop: 使用简单的for循环:
var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
// Using $() to re-wrap the element.
$(testimonials[i]).text('a');
}