jQuery的each()
方法是一个通用的迭代器函数,用于遍历和操作jQuery对象集合中的每个元素。它可以用来循环遍历DOM元素、数组或对象。
// 遍历jQuery对象
$(selector).each(function(index, element) {
// 操作代码
});
// 通用遍历(数组或对象)
$.each(collection, function(index, value) {
// 操作代码
});
在jQuery的each()
方法中,选择器用于确定要遍历的元素集合。常见的选择器类型包括:
$("div").each()
- 遍历所有div元素$(".class").each()
- 遍历所有具有指定class的元素$("#id").each()
- 遍历具有指定ID的元素$("ul li").each()
- 遍历ul下的所有li元素$("div > p").each()
- 遍历div直接子元素中的p元素$("li:first").each()
- 遍历第一个li元素$("tr:even").each()
- 遍历偶数行tr元素$("input:text").each()
- 遍历所有文本输入框// 遍历所有段落并添加类
$("p").each(function(index) {
$(this).addClass("paragraph-" + index);
});
// 遍历数组
var arr = ["a", "b", "c"];
$.each(arr, function(index, value) {
console.log(index + ": " + value);
});
// 遍历对象
var obj = { name: "John", age: 30 };
$.each(obj, function(key, value) {
console.log(key + ": " + value);
});
问题1:each()循环中this的指向
$(this)
转换为jQuery对象$("div").each(function() {
// 错误:this.css()会报错,因为this是DOM元素
// 正确:
$(this).css("color", "red");
});
问题2:如何提前终止each()循环
$("div").each(function(index) {
if (index === 2) {
return false; // 相当于break
}
console.log(index);
});
问题3:性能问题
// 优化前(每次循环都重新查询DOM)
for (var i = 0; i < 10; i++) {
$(".items").each(function() { /*...*/ });
}
// 优化后(只查询一次DOM)
var $items = $(".items");
for (var i = 0; i < 10; i++) {
$items.each(function() { /*...*/ });
}
问题4:异步操作问题
// 错误示例(异步操作不会按预期顺序执行)
$("img").each(function() {
loadImage($(this).attr("src"), function() {
console.log("loaded");
});
});
// 正确解决方案之一
var promises = [];
$("img").each(function() {
promises.push(new Promise(function(resolve) {
loadImage($(this).attr("src"), resolve);
}));
});
Promise.all(promises).then(function() {
console.log("all images loaded");
});
jQuery的each()
方法结合选择器提供了强大而灵活的遍历功能,是jQuery开发中最常用的方法之一。