今天又迷惘了一次,决定把这玩意记下来:
1、通用的each
这种格式主要用于jquery的对象中,也可以用于数组。each前面没有jquery对象,只有jquery的标志:
-
格式:jQuery.each( array, callback )
-
-
array
-
Type: Array
-
The array to iterate over.
-
callback
-
Type: Function( Integer indexInArray, Object value )
-
The function that will be executed on every object.
-
jQuery.each( object, callback )
-
object
-
Type: Object
-
The object to iterate over.
-
callback
-
Type: Function( String propertyName, Object valueOfProperty )
-
The function that will be executed on every object.
-
-
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 thethiskeyword, but Javascript will always wrap thethisvalue as anObjecteven if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
用法示例:
-
var obj = {
-
"flammable": "inflammable",
-
"duh": "no duh"
-
};
-
$.each( obj, function( key, value ) {
-
alert( key + ": " + value );
-
});
2、dom的eache,主要用于dom结构中,在对象和数组中有时不好用,需要认清使用的目标:
-
Description: Iterate over a jQuery object, executing a function for each matched element.
-
-
version added: 1.0.each( function )
-
function
-
Type: Function( Integer index, Element element )
-
A function to execute for each matched element.
-
-
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.
示例:
-
// The .each() method is unnecessary here:
-
$( "li" ).each(function() {
-
$( this ).addClass( "foo" );
-
});
-
// Instead, you should rely on implicit iteration:
-
$( "li" ).addClass( "bar" );
阅读(1768) | 评论(0) | 转发(0) |