$('.testimonial').each(function(){
//if statement here
// use $(this) to reference the current div in the loop
//you can try something like...
if(condition){
}
});
$('div[class="testimonial"]').each(function(index,item){
if(parseInt($(item).data('index'))>2){
$(item).html('Testimonial '+(index+1)+' by each loop');
}
});
var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
var element = testimonialElements.eq(i);
//do something with element
}
var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(elements, index) {
// conditional here.. access elements
});
26
使用简单的for循环:
var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
// Using $() to re-wrap the element.
$(testimonials[i]).text('a');
}
14 回答
试试这个...
试试这个例子
Html
当我们想要访问那些
data-index
大于2
的divs
时,我们需要这个jquery .Working example fiddle
jQuery's .eq()可以帮助您使用索引方法遍历元素 .
更确切:
在JavaScript ES6 中使用spread ... operator
Element.querySelectorAll()
给出的 array-like 集合我可能会遗漏部分问题,但我相信你可以这样做:
你可以这样做
使用每个:'
i
'是数组中的位置,obj
是您正在迭代的DOM对象(也可以通过jQuery包装器$(this)
访问) .有关更多信息,请查看api reference .
这些天没有jQuery这样做很简单 .
没有jQuery:
只需选择元素并使用.forEach() method迭代它们:
使用简单的for循环:
您可以使用.filter简明扼要地完成此操作 . 以下示例将隐藏包含单词"something"的所有.testimonial div:
Without jQuery updated