jquery的each

jQuery 的 each 方法
jQuery 的 each() 方法用于遍历 jQuery 对象或普通数组/对象,对每个元素执行回调函数。以下是两种主要用法:
遍历 jQuery 对象
$('selector').each(function(index, element) {
// index: 当前元素的索引
// element: 当前 DOM 元素(非 jQuery 对象)
// 使用 $(element) 转换为 jQuery 对象
});
遍历普通数组或对象
$.each(arrayOrObject, function(indexOrKey, value) {
// 对数组:index 是数字索引,value 是元素
// 对对象:index 是键名,value 是键值
});
示例代码
遍历列表项
$('li').each(function(i, el) {
console.log(`索引 ${i}: 内容为 ${$(el).text()}`);
});
遍历数组
var colors = ['red', 'green', 'blue'];
$.each(colors, function(i, color) {
console.log(`颜色 ${i}: ${color}`);
});
遍历对象
var person = { name: 'Alice', age: 25 };
$.each(person, function(key, value) {
console.log(`${key}: ${value}`);
});
注意事项
- 在
$.each中可以通过返回false提前终止循环 - 原生 DOM 元素需用
$(element)包装才能使用 jQuery 方法 - 对于 jQuery 集合,
each()是实例方法;对于普通数据,$.each()是工具方法
性能提示
- 简单遍历优先考虑原生
for循环 - 大量数据操作时,jQuery 的
each可能比原生循环稍慢







