jQuery的each()方法是一个非常实用的方法,可以用来循环遍历jQuery对象。它的语法是:
$(selector).each(function(index, element)) { // 代码块 });
其中,参数index是当前循环的索引,参数element是当前循环的元素,比如:
$('div').each(function(index, element) { console.log(index); console.log(element); });
第一次循环,index的值为0,element的值为第一个div元素;第二次循环,index的值为1,element的值为第二个div元素,以此类推。
each()方法可以用来遍历一个jQuery对象,也可以用来遍历一个数组,比如:
var arr = [1, 2, 3]; $.each(arr, function(index, element) { console.log(index); console.log(element); });
第一次循环,index的值为0,element的值为1;第二次循环,index的值为1,element的值为2,以此类推。
each()方法还可以用来遍历一个对象,比如:
var obj = {name: 'John', age: 20}; $.each(obj, function(key, value) { console.log(key); console.log(value); });
第一次循环,key的值为'name',value的值为'John';第二次循环,key的值为'age',value的值为20,以此类推。
each()方法的返回值
each()方法返回一个jQuery对象,可以链式调用,比如:
var arr = [1, 2, 3]; var result = $.each(arr, function(index, element) { console.log(index); console.log(element); }); console.log(result); // [1, 2, 3]
可以看到,each()方法返回的是一个数组,即被遍历的元素。
each()方法的使用场景
each()方法可以用来遍历jQuery对象、数组、对象,可以用来实现一些常见的功能,比如:
- 遍历jQuery对象,获取元素的属性,比如:
$('div').each(function(index, element) { var width = $(element).width(); console.log(width); });
- 遍历数组,计算数组元素的和,比如:
var arr = [1, 2, 3]; var sum = 0; $.each(arr, function(index, element) { sum += element; }); console.log(sum); // 6
- 遍历对象,把对象转换为字符串,比如:
var obj = {name: 'John', age: 20}; var str = ''; $.each(obj, function(key, value) { str += key + '=' + value + '&'; }); console.log(str); // name=John&age=20&
each()方法是一个非常实用的方法,可以用来实现循环遍历jQuery对象、数组、对象,它的语法简单易懂,易于上手,可以大大提高开发效率。