Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using jQuery .each(), is it possible to use a non-anonymous function?

I have this code block I find particularly long and hard to udnerstood : the call stack is full of implicit functions and paramters implicitely added to it. in other words, i would like to clarify my code by separating the function called in the each from the each itself.

Look that example :

$(xml).find('group').each(function () {
    var groupName = $(this).attr('name');
    // There is here around 100 lines of codes I would like to split in 
    // at least five functions, And I'm sure it is possible to use named functions
    // instead of implicit ones, no ?
like image 211
Riduidel Avatar asked Apr 18 '13 15:04

Riduidel


People also ask

What is an anonymous function in JavaScript?

An anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

What is the use of each() function in jQuery?

What is the use of .each () function in jQuery ? The each () function in jQuery iterate through both objects and arrays. Arrays that have length property are traversed from the index 0 to length-1 and whereas arrays like objects are traversed via their properties names. $.each ('array or object', function (index, value) { // Your code })

What is the first argument of each in jQuery?

This means that there’s no strict equality between the value and the context. The first argument is the current index, which is either a number (for arrays) or string (for objects). 1. Basic jQuery.each () Function Example

What is jQuery used for in JavaScript?

It’s very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties. In addition to this function, jQuery provides a helper function with the same name that can be called without having previously selected or created any DOM elements.


2 Answers

Try passing function reference

Live Demo

$(xml).find('group').each(myfun);

function myfun(i, item)
{
    alert(item.id);
}
like image 100
Adil Avatar answered Oct 23 '22 09:10

Adil


You could also just do:

$(xml).find('group').each(function(){
    yourFunction();
});
like image 3
iamtooamazing Avatar answered Oct 23 '22 10:10

iamtooamazing