jQuery的each()方法怎么使用

小億
102
2023-09-05 14:06:43

jQuery的each()方法用于遍歷集合中的每個(gè)元素,并對(duì)每個(gè)元素執(zhí)行指定的函數(shù)。

語(yǔ)法:

$.each(collection, function(index, value){
// 執(zhí)行的代碼
});

參數(shù)說(shuō)明:

  • collection:要遍歷的集合(數(shù)組、對(duì)象、類數(shù)組對(duì)象等)。

  • function(index, value):對(duì)每個(gè)元素執(zhí)行的函數(shù)。其中index是元素的索引,value是元素的值。

示例:

var arr = [1, 2, 3, 4, 5];
$.each(arr, function(index, value){
console.log("索引:" + index + ",值:" + value);
});

輸出:

索引:0,值:1
索引:1,值:2
索引:2,值:3
索引:3,值:4
索引:4,值:5

另外,each()方法也可以用于遍歷對(duì)象的屬性。

var obj = {name: "Alice", age: 20};
$.each(obj, function(key, value){
console.log("屬性:" + key + ",值:" + value);
});

輸出:

屬性:name,值:Alice
屬性:age,值:20

0