我有一个div与类的证明,我想用jquery循环通过他们检查每个div如果一个特定的条件是真的负载。如果为真,它应该执行一个操作。
有人知道我会怎么做吗?
我有一个div与类的证明,我想用jquery循环通过他们检查每个div如果一个特定的条件是真的负载。如果为真,它应该执行一个操作。
有人知道我会怎么做吗?
当前回答
$('.testimonal').each(function(i,v){
if (condition) {
doSomething();
}
});
其他回答
更精确的:
$.each($('.testimonal'), function(index, value) {
console.log(index + ':' + value);
});
$('.testimonal').each(function(i,v){
if (condition) {
doSomething();
}
});
现在不使用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
});
使用每个:'i'是数组中的位置,obj是你正在迭代的DOM对象(也可以通过jQuery包装器$(this)访问)。
$('.testimonial').each(function(i, obj) {
//test
});
查看api参考以获得更多信息。
你可以这样做
$('.testimonial').each(function(index, obj){
//you can use this to access the current item
});