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 );
});
2008年9月4日 星期四
$.each
jquery each find what is different
[html]
<div id="'test'">
<span id="'each'">(click here to change)</span>
<ul>
<li class="cc">Eat</li>
<li class="cc">Sleep</li>
<li class="bb">Be merry</li>
</ul>
</div>
[script 1]
$("#test span").click(function () {
if ($("#test").find('li')) {
alert($(this).html());
}
});
$(this) is $(#test span)
[script 2]
$("#test span").click(function () {
if ($("#test li")) {
alert($(this).html());
}
});
$(this) is $(#test span)
[script 3]
$("#test span").click(function () {
$("#test li").each(function(i, e){
alert($(this).html());
}
});
$(this) is really every li tag
i is the iterator counter
e == $(this)
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).
訂閱:
文章 (Atom)