jQuery API jQuery API 中英文对照版 - jQuery在线查询手册
each(fn)

each(fn)

以每一个匹配的元素作为上下文来执行一个函数。这意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的元素(每次都是一个不同的匹配元素)。

而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数。

返回值:jQuery

参数:

  • fn (Function): 要执行的函数
 
示例:

迭代两个图像,并设置它们的src属性。

HTML 代码:

<img/><img/>

jQuery 代码:

$("img").each(function(i){ this.src = "test" + i + ".jpg"; });

结果:

<img src="test0.jpg"/><img src="test1.jpg"/>

 
each( fn )

Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.

Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).

Return value: jQuery
Parameters:

  • fn (Function): A function to execute
 

Example:

Iterates over two images and sets their src property

 $("img").each(function(i){     this.src = "test" + i + ".jpg";   });  
Before:
 <img/><img/>  
Result:
 <img src="test0.jpg"/><img src="test1.jpg"/>

If you want to have the jquery element instead of the dom element, uses the $(this) function. eg.

$("img").each(function(i){
    $(this).toggleClass("example");
    //of course, that's more useful when you have something more complex to do than just toggling a class?;)
  });