jQuery循环使用相同类的元素

本文翻译自: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? 有谁知道我会怎么做?


#1楼

参考:https://stackoom.com/question/JrsU/jQuery循环使用相同类的元素


#2楼

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
}

#3楼

It's pretty simple to do this without jQuery these days. 这些天没有jQuery这样做很简单。

Without jQuery: 没有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
});

#4楼

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 工作范例小提琴


#5楼

More precise: 更确切:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});

#6楼

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');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值