$.each () and $ (selector). each () is very stage-like, but it is not the same.
The former can be used to iterate over an array or JSON object
The latter is designed to traverse the jquery object
The first one is $.each () Yes, usually so.
$.each (arr, function (i, v) {//Do something})
Where Arr is a collection, it can also be a JSON object
And I in the callback function is the subscript of the array (the corresponding key in JSON)
and V is the value of Arr[i] (corresponding value in JSON)
Here's a simple example:
var json = {name: "Zhu", age:10}var arr = [' A ', ' B ', ' C ', ' d ']$.each (arr, function (i, v) {alert (i + ":" + V)}); $.each (JSON, fun Ction (k, v) {alert (k + ":" + V)});
This completes the traversal of the array and JSON.
Of course, so the traversal with the native JS is also easy to do
For example, traversing the above JSON or ARR requires only:
For (var k in JSON) {alert (k + ":" + Arr[k])}
It seems that JS is more concise some of the performance may be better
The following describes $ (selector). each (). This method can not find a substitute in JS.
$ (selector) is responsible for selecting a set of jquery elements, and each function is responsible for traversing it
For example, we want to change the text color of a group of "Li"
<style>.red{color:red;} </style><ul><li>Dog</li><li>Cat</li><li>Mouse</li></ul> <input type= "button" id= "BTN" ><script>$ ("#btn"). Click (function () {$ ("Li"). each (function () {$ (this). Toggleclass (' Red ');}); </script>
Just actually, there's an implicit iteration in jquery.
Whenever we call the Selector method to find an element in the DOM tree, we actually put the found DOM element into a DOM array in a jquery object and then return the jquery object.
The so-called implicit iteration is when we call the JQuery method (such as Toggleclass (..) )。 The jquery method iterates through the inner Dom array. and calls the corresponding DOM property or method of each DOM element to complete the operation.
All the functions in the Click Do not need to use each, direct $ ("Li"). Toggleclass (' red ') can also
In $ (seletor). Each (..) In This is bound to the currently traversed DOM object, and if you need to get the jquery object $ (this) you can
It is worth noting that the early exit traversal, can also traverse, only need to return false on the above
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
jquery Intermediate each embodiment of the method