JQuery.each (function (index, value) {}); What is value?

I am learning jQuery from a book called Head First jQuery . From the book is very easy to learn. The fact is that there is a function .each() (included in the image that I scanned from), which has a function () parameter. Function parameters (): index and value . The index is explained on the page, but what about value? And also, since this is an anonymous function (which cannot be reused), how does it accept any parameters?

+8
jquery
source share
2 answers

JQuery has two methods each . One of them is designed to cycle through a jQuery object that contains many matches. For example, suppose we wanted to find all the paragraphs on a page:

 $("p").each(function(){ // Do something with each paragraph }); 

Secondly, there is a more general each for iterating over objects or arrays:

 var names = ["Jonathan", "Sampson"]; $.each(names, function(){ // Do something with each name }); 

When jQuery cycles through the elements in any of these examples, it counts which object it processes. When it performs our anonymous function, it passes two parameters: the current value that we find (index), and this object (value).

 var names = ["Jonathan", "Sampson"]; $.each(names, function(index, value){ alert( value + " is " + index ); }); 

Which outputs are "Jonathan is 0" and "Sampson is 1", since we use an index based on zero.

But what about our own jQuery object?

 $("p").each(function(index, value){ alert( value.textContent ); // The text from within the paragraph }); 

In this case, value is the actual HTMLParagraphElement object, so we can access properties like textContent or innerText if you want:

+17
source share

This second parameter, which you called the value, is the value of the collection that is currently being processed by each function.

For your second question, anonymous functions can be reused, just because they do not have a name, this does not mean that they cannot have parameters or execute. See the following example:

 function execute_fn(fn) { fn(1,2); } execute_fn(function(a,b) { ... }); 
+1
source share

All Articles