📅  最后修改于: 2023-12-03 15:16:41.880000             🧑  作者: Mango
Jquery is a popular JavaScript library that allows developers to manipulate HTML elements, CSS styles, and handle events easily. One of the most important features of Jquery is its ability to iterate over collections of elements.
In this tutorial, we will discuss how to iterate over an object in Jquery using the $.each()
function.
$.each()
FunctionThe $.each()
function is a shorthand version of a for loop
in JavaScript. It allows you to iterate over an object, array, or list of elements.
The basic syntax of the $.each()
function is as follows:
$.each(object, function(index, value){
// callback code here
});
object
: The object, array or list to iterate over.function(index, value)
: A callback function to handle each iteration.index
: The index of the current element in the object.value
: The value of the current element in the object.Let's take a look at an example.
<!DOCTYPE html>
<html>
<head>
<title>Jquery Iterate Object</title>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
var obj = {
"name": "John",
"age": 30,
"city": "New York"
};
$.each(obj, function(key, value){
console.log(key + ": " + value);
$("#result").append('<li>' + key + ': ' + value + '</li>');
});
});
</script>
</head>
<body>
<h1>Jquery Iterate Object Example</h1>
<ul id="result">
<!-- results appear here -->
</ul>
</body>
</html>
In this example, we create an object obj
with three properties (name
, age
and city
). We then use the $.each()
function to iterate over the properties of the object, logging each key-value pair to the console and appending them to an unordered list on the page.
The output should look something like this:
name: John
age: 30
city: New York
Iterating over objects in Jquery is a powerful way to handle data structures in your code. The $.each()
function makes it easy to loop through an object, array or list of elements, allowing you to manipulate and work with the data in a variety of ways.