温馨提示×

jquery中each的遍历方法有哪些

小亿
86
2023-08-04 09:32:30
栏目: 编程语言

在jQuery中,可以使用以下几种方法来遍历元素集合:

  1. $.each()方法:使用$.each()方法可以遍历数组或对象。

示例:

var array = [1, 2, 3];
$.each(array, function(index, value) {
console.log(index, value);
});
var object = {name: "John", age: 30};
$.each(object, function(key, value) {
console.log(key, value);
});
  1. .each()方法:使用.each()方法可以遍历元素集合。

示例:

$("li").each(function(index, element) {
console.log(index, element);
});
  1. .map()方法:使用.map()方法可以遍历元素集合,并返回一个新的数组。

示例:

var newArray = $("li").map(function(index, element) {
return index;
});
console.log(newArray);
  1. .find()方法:使用.find()方法可以遍历匹配元素的后代元素。

示例:

$("ul").find("li").each(function(index, element) {
console.log(index, element);
});

需要注意的是,以上方法中的回调函数可以接收两个参数:index为当前元素在集合中的索引,element为当前元素的DOM对象。

0