本文共 1629 字,大约阅读时间需要 5 分钟。
本文翻译自:
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? 有谁知道我会怎么做?
参考:
can help you traverse through elements with an indexed approach. 可以帮助您使用索引方法遍历元素。
var testimonialElements = $(".testimonial");for(var i=0; i
It's pretty simple to do this without jQuery these days. 这些天没有jQuery这样做很简单。
Just select the elements and use the to iterate over them: 只需选择元素并使用迭代它们:
var testimonials = document.querySelectorAll('.testimonial');Array.prototype.forEach.call(testimonials, function(elements, index) { // conditional here.. access elements});
Try this example 试试这个例子
Html HTML
Testimonial 1Testimonial 2Testimonial 3Testimonial 4Testimonial 5
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'); }});
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');}
转载地址:http://bscnb.baihongyu.com/