📅  最后修改于: 2023-12-03 15:15:10.314000             🧑  作者: Mango
Foreach is a loop used to iterate over a collection of elements or values. In jQuery, the .each()
method provides the implementation of the foreach loop. It can be used to iterate over arrays, objects, or jQuery collections.
The syntax for using .each()
method is as follows:
$(selector).each(function(index, element){
// code to be executed for each iteration
});
selector
: A string containing a selector expression or a jQuery object containing elements to be iterated over.index
: An optional parameter representing the index of the current iteration.element
: An optional parameter representing the current element being iterated over.let fruits = ["apple", "banana", "cherry", "orange"];
$.each(fruits, function(index, value){
console.log(index + ": " + value);
});
Output:
0: apple
1: banana
2: cherry
3: orange
let person = {name: "John", age: 30, city: "New York"};
$.each(person, function(key, value){
console.log(key + ": " + value);
});
Output:
name: John
age: 30
city: New York
$(".fruits").each(function(index, element){
console.log(index + ": " + $(element).text());
});
HTML:
<ul>
<li class="fruits">apple</li>
<li class="fruits">banana</li>
<li class="fruits">cherry</li>
<li class="fruits">orange</li>
</ul>
Output:
0: apple
1: banana
2: cherry
3: orange
The .each()
method in jQuery provides a simple and easy way to iterate over collections in Javascript. It can be used to iterate over arrays, objects, or jQuery collections.