jQuery: .each(function)

Iterate over a jQuery object, executing a function for each matched element.

.each(function)

function

type: Function(Integer index, Element element)

a function to execute for each matched element

 

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,begginning from 0.

the callback is fired in the context of the current DOM element, so the keyword this refers to the element.this == element

example:

<ul>

  <li>foo</li>

  <li>bar</li>

</ul>

$('li').each(function(index){

console.log(index + ": " + $(this).text());

})

输出:

0: foo

1: bar

you can stop the loop from within the callback function by returning false.

$( "div" ).each(function( index, element ) {
  // element == this
  $( element ).css( "backgroundColor", "yellow" );
  if ( $( this ).is( "#stop" ) ) {
    $( "span" ).text( "Stopped at div index #" + index );
    return false;
  }
});

 

posted @ 2016-05-12 16:16  Carolina  阅读(359)  评论(0编辑  收藏  举报