jQuery是一个快速、简洁的JavaScript库,它简化了HTML文档遍历、事件处理、动画和Ajax交互等操作,在jQuery中,我们可以使用多种方法来循环遍历集合,例如.each()、.map()、.filter()等,本文将详细介绍如何使用这些方法进行循环遍历。

1、.each()方法
.each()方法是jQuery中最常用的循环遍历方法,它可以遍历一个数组或对象,并对每个元素执行指定的函数,基本语法如下:
$(selector).each(function(index, element))
selector是要遍历的元素选择器,function(index, element)是每次遍历时要执行的回调函数,index表示当前元素的索引,element表示当前遍历到的元素。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>jQuery Each Example</title>
<script src="https://code.jquery.com/jquery3.6.0.min.js"></script>
</head>
<body>
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
<script>
$(document).ready(function() {
$("#fruits li").each(function(index, element) {
console.log("Fruit: " + $(element).text());
});
});
</script>
</body>
</html>
在这个示例中,我们使用.each()方法遍历id为"fruits"的无序列表中的每个列表项,并在控制台输出每个水果的名称。
2、.map()方法
.map()方法也是jQuery中常用的循环遍历方法,它可以遍历一个数组或对象,并对每个元素执行指定的函数,然后将结果组成一个新的数组返回,基本语法如下:
$(selector).map(function(index, element))
selector是要遍历的元素选择器,function(index, element)是每次遍历时要执行的回调函数,index表示当前元素的索引,element表示当前遍历到的元素,与.each()方法不同的是,.map()方法会返回一个新的数组,而不会修改原始数组。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>jQuery Map Example</title>
<script src="https://code.jquery.com/jquery3.6.0.min.js"></script>
</head>
<body>
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
<script>
$(document).ready(function() {
var fruits = $("#fruits li").map(function(index, element) {
return $(element).text();
}).get(); // 将生成的数组转换为普通数组
console.log(fruits); // 输出:["Apple", "Banana", "Orange"]
});
</script>
</body>
</html>
在这个示例中,我们使用.map()方法遍历id为"fruits"的无序列表中的每个列表项,并将每个水果的名称组成一个新的数组返回,然后我们将生成的jQuery对象数组转换为普通数组,并在控制台输出。
3、.filter()方法
.filter()方法也是jQuery中常用的循环遍历方法,它可以遍历一个数组或对象,并根据指定条件筛选出符合条件的元素,基本语法如下:
$(selector).filter(function(index, element))
selector是要遍历的元素选择器,function(index, element)是每次遍历时要执行的回调函数,index表示当前元素的索引,element表示当前遍历到的元素,与前两种方法不同的是,.filter()方法会返回一个新的jQuery对象,包含筛选出的元素,如果需要返回普通数组,可以使用.get()方法。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>jQuery Filter Example</title>
<script src="https://code.jquery.com/jquery3.6.0.min.js"></script>
</head>
<body>
<ul id="fruits">
<li class="apple">Apple</li>
<li class="banana">Banana</li>
<li class="orange">Orange</li>
<li class="grape">Grape</li>
</ul>
<script>
$(document).ready(function() {
var filteredFruits = $("#fruits li").filter(function(index, element) {
return $(element).hasClass("apple"); // 筛选出class为"apple"的元素
}).get(); // 将生成的jQuery对象数组转换为普通数组
console.log(filteredFruits); // 输出:["Apple"](文本内容)和[object HTMLLIElement](DOM元素)组成的数组(根据浏览器不同)
});
</script>
</body>
</html>