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 ?
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 ? 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 })
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
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.
Try passing function reference
Live Demo
$(xml).find('group').each(myfun);
function myfun(i, item)
{
alert(item.id);
}
You could also just do:
$(xml).find('group').each(function(){
yourFunction();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With