Implementing JQuery.each () / $.each () function and differentiating it from $().each ()


           JQuery.each () utility method is a generalized iterator method which loops through both arrays and objects. An example for object here is a collection. It uses the length property of the arrays as an index for iteration starting from 0 to length-1.And considers the name property for all the other objects to loop through.
This can also be coded as $.each (), which is the most popular and simplified way.

Note: There is a significant difference between $.each () and $().each () methods. They are not interchangeable.

$.each ()
$().each ()
This is a utility method.
This is a traversing method.
This is used to iterate over arrays and objects.
This is used to traverse through DOM elements and iterate over matched JQuery Objects list.
Syntax:$.each(object, callback)
Syntax:$(selector).each(callback)
This is a generalized method, which iterates over any Objects.
This is a specific method, which works only on JQuery Objects.

Now let us understand the syntax $.each (object, callback) in detail.
The object here represents any array or collection. The callback is a function which takes two parameters, as below.
$.each (object, function (index, item)
{
});

The index is the index of the element in the array starting from 0, and the item is the element itself.
When the object represents a collection, the first parameter and second parameter of callback method represents the key and the value respectively.
To implement this utility method let us create an array and collection, and bind their values to two different divs’. 

Step 1: 
         Download JQuery Library from https://jquery.com/download/ and copy the files to one of          your project folders as below. I have added minified version of JQuery here, you can add the full   version if you want.


 Step 2:
          Add a Web Form to the website as below and name it as Home.aspx.


Step 3
          Add reference of JQuery file to Home.aspx as shown below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/Scripts.js" type="text/javascript"></script>
</head>

Step 4
         Now create two div tags with ids’, one for showing the array contents and the second one is for showing the collection contents.
<body>
    <form id="form1" runat="server">
    <div id="colorInfo">    
    </div>
    <div id="numberInfo"></div>
    </form>
</body>
</html>

Here I am going to bind the array with different colour names, to the div “#colorInfo”, and  bind the collection with numbers, to the div “#numberInfo”.

Step 5: To define the array and collection and bind them back to the divs’ , let us create a separate JavaScript file, and add it’s reference to the Home.aspx ,just as you did for JQuery library file, as below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/Scripts.js" type="text/javascript"></script>
</head>


Step 6: Now open up the JavaScript file that we created in step 5 and start writing the code as below.
$(document).ready(function () {

    var colorArray = ["Green", "Blue", "Orange", "Gray"]
    var numberCollection = { 1: "first", 2: "second", 3: "three", 4: "four" };

    /*Setting the background color for colorInfo div*/
    $("#colorInfo").css("background-color", "gray");
    /*running the each loop over colorArray*/
    $.each(colorArray, function (index, item) {
        $("#colorInfo").append('<li>' + "The colour is: " + item + " at the index " + index + '</li>');

    });

    /*Setting the background color for numberInfo div*/
    $("#numberInfo").css("background-color", "yellow");
    /*running the each loop over numberCollection*/
    $.each(numberCollection, function (item, index) {
        $("#numberInfo").append('<li>' + "The value is: " + index + " with the key " + item + '</li>');

    });

});

In the above code we are initiating a colorArray and a numberCollection with some values in it. Just to show the difference between the divs’, I am trying to assign a different back ground colour for each one, using “.css” method of JQuery. If you compare the below line of code with the actual syntax,
 /*running the each loop over colorArray*/
    $.each(colorArray, function (index, item) 

The object is the colorArray and the callback is the anonymous function, which is having two parameters. In this instance the $.each method treats the first parameter as index of the array, which starts from 0 and treats the second parameter as element.

If you observe the numberCollection and the each loop running on it,
var numberCollection = { 1: "first", 2: "second", 3: "three", 4: "four" };
 /*running the each loop over numberCollection*/
    $.each(numberCollection, function (item, index)

The $.each() method in this instance understands the object passed is a key value pair and treats the first parameter as  key which is  “1” and the second parameter as  value which is “first” and so on….

You must be wondering, how is this treatment of Object changes without any external specification.
Well that’s the magic of $.each (), it changes the treatment depending up on the type of object you are passing; you absolutely no need to tell anything to it.

Within the each method, we are finding the div based on its id and binding the data to it.
Hence you get the following output.


Note: The parameter names need not to be always index, item or key, value. You can use whatever meaningful name you want.

Source code of this application : Link



Reactions:

0 comments :

Post a Comment