What is the difference between this:
$.each($(\'#myTable input[name=\"deleteItem[]\"]:checked\').do_something());
and this:
The first will run the callback function to the elements in the collection you've passed in, but your code is not syntactically correct at the moment for it.
It should be:
$.each($('#myTable input[name="deleteItem[]"]:checked'), do_something);
See: http://api.jquery.com/jQuery.each/
The second will run the function on each element of the collection you are running it on.
See: http://api.jquery.com/each/
Taken from http://api.jquery.com/jQuery.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, 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.
In the first case you can iterate over jQuery objects and also other array items as indicated here:
jQuery.each()
In the second case you can only itterate over jQuery objects as indicated here:
.each()
From what I understand $.each();
loops through an object or array and gives you the iterator and value of each item.
$().each();
loops through a list of jQuery objects and gives you the iterator and the jQuery object.
Description:
.each
is an iterator that is used to iterate over only jQuery objects collection whilejQuery.each
($.each
) is a general function for iterating over JavaScript objects and arrays.
$.each()
functionvar myArray = [10,20,30];
$.each( myArray, function(index, value) {
console.log('element at index ' + index + ' is ' + value);
});
//Output
element at index 0 is 10
element at index 1 is 20
element at index 2 is 30
.each()
method$('#dv').children().each(function(index, element) {
console.log('element at index ' + index + 'is ' + (this.tagName));
console.log('current element as dom object:' + element);
console.log('current element as jQuery object:' + $(this));
});
//Output
element at index 0 is input
element at index 1 is p
element at index 2 is span
You want to really use $.each
with an array that isn't elements or something. ie:
var x = ["test", "test2"];
You'd use $.each(x...
to traverse that instead of x.each
:)
.each
is for elements only :)