怎么在jquery中遍历集合
发布时间:2026-11-30 10:15:50

1、历集.each() 方法

怎么在jquery中遍历集合

.each() 方法(fa)用于遍历jQuery对象集合,中遍它接受一个回调函数作(zuo)为参数,历集该回调函数会在每个元素上执行,中遍回调函数可(ke)以接受两个参数:第一个参数是历集当(dang)前元素的索引,第二个参数是中遍当前元素本身(shen)。

怎么在jquery中遍历集合

示例:

怎么在jquery中遍历集合

$("li").each(function(index,历集 element) {  console.log("Index: " + index + ", Element: " + $(element).text());});

2、.forEach() 方(fang)法

.forEach() 方法是中遍ES6中的新特性,也可以用于遍历jQuery对象(xiang)集合,历集它与.each()类似,中遍但使(shi)用箭头函数时,历集不需要显式地传(chuan)递索引和元素参数。中遍

示(shi)例:

$("li").toArray().forEach((element) => {  console.log("Element: " + $(element).text());});

3、.map() 方法

.map() 方(fang)法用于(yu)将jQuery对象集合转换为一个新的数组,它接受一个回调函数(shu)作(zuo)为参数,该回调(diao)函数会在每个元素上执行,回调函数的返回值将被添加到新的数组中。

示例:

const newArray = $("li").map(function() {  return $(this).text();}).get();console.log(newArray);

4、.filter() 方法

.filter() 方法用于(yu)根据指定的条件筛选jQuery对象集合,它接受一个回调函数作为参数,该回调函数会(hui)在每个元素上执行,如果回调函数返回true,则该元素将被保留在(zai)新集(ji)合(he)中。

示例:

const filteredList = $("li").filter(function() {  return $(this).text().includes("selected='selected'");});console.log(filteredList);

5、.find() 方法和(he) .children() 方法

.find() 方法用于在jQuery对象集合的子元素中查找匹配的元素。.children() 方法用于获取直接子元素,这两个方法都可(ke)以接(jie)受选择器(qi)字符串作为参(can)数。

示(shi)例:

// 使用 .find() 方法const foundItems = $("ul").find("li");// 使用 .children() 方法(fa)const directChildren = $("ul").children("li");

通过以上方(fang)法,你可以在(zai)jQuery中轻松地遍历集合,根据你的需(xu)求选择合(he)适的方法,并结合(he)回调函数实现(xian)复杂的操作。