Jquery $.each selector

2020-07-16 12:49发布

问题:

I would like to know what $.each() stands for in jquery,
What is it selecting?

Is there an equivalent in prototype?

回答1:

$.each() isn't selecting anything. It is just a utility to iterate over a collection.

When you do:

$('someSelector').each(function() {
    // do something
});

jQuery is internally calling:

jQuery.each( this, callback, args );

...with this representing the matched set.

http://github.com/jquery/jquery/blob/master/src/core.js#L231

You could just as easily call it yourself manually.

jQuery.each( $('someSelector'), function() {
    // do something
});


回答2:

I think you should rather look at

jQuery.each()

From the documentation

The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword.)



回答3:

It is used to iterate exclusively, over a jQuery object. It can be used to iterate over any collection, see the documentation for jQuery.each.



回答4:

jQuery uses each in two ways:

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

refer .each()

The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword.)

$.each()



回答5:

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated. 1 2 3

$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});

This produces two messages:

0: 52 1: 97