2008年9月4日 星期四

$.each


This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.

The callback has two arguments:the key (objects) or index (arrays) as the first, and the value as the second.

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});

My id is one. - 1
My id is two. - 2
My id is three. - 3
My id is four. - 4
- 5



#Iterates over items in an array, accessing both the current item and its index.

$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});



#Iterates over the properties in an object, accessing both the current item and its key.

$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});

沒有留言: