JQueryのeach関数ノート1
3946 ワード
//
jQuery.each( collection, callback(indexInArray, valueOfElement) )
//collection The object or array to iterate over.
//collection
//callback(indexInArray, valueOfElement) The function that will be executed on every object.
//callback(indexInArray, valueOfElement) ,
//-- indexInArray /
//-- valueOfElement
//Summary
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
/*
, , ( ) , 0 length-1 , ( map ) 。
*/
//
The $.each() function is not the same as $(selector).each()....
// $.each() $(selector).each(), 。
//$(selector).each() http://api.jquery.com/each/
//
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
//output result:
//0: 52
//1: 97
//Map
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
//output result:
//flammable: inflammable
//duh: no duh
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
/*
$.each() , return false ,continue
*/
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
div#five { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
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("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
</script>
</body>
</html>
Mine is one. - 1
Mine is two. - 2
Mine is three. - 3
- 4
- 5
//
Example: Iterates over items in an array, accessing both the current item and its index.
$.each( ['a','b','c'], function(i, l){
alert( "Index #" + i + ": " + l );
});
Example: Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Key: " + k + ", Value: " + v );
});