상세 컨텐츠

본문 제목

.each()

jquery test

by binbing 2018. 1. 9. 14:18

본문


설명 : 일치하는 각 요소에 대해 함수를 실행하여 jQuery 객체를 반복






Type: Function( Integer index, Element element )

Integer : 정수

Element : 요소





  • foo
  • bar
$( "li" ).each(function( index ) { console.log( index + ": " + $( this ).text() ); });




console창에 나온 값은

0: foo
1: bar

0과 1은 index의 값이란 것을 알 수가 있다.





//이렇게 .each()로 li태그 각 요소를 반복시키면서 class="foo" 클래스가 추가된 것을 확인할 수 있지만
$( "li" ).each(function( index ) {
  	$( this ).addClass( "foo" );
});

$("li").addClass("foo"); //로 쓰는 것이 간결하다.







.each() 테스트를 해보자면


$( "button" ).click(function() { //버튼을 클릭하면
  $( "div" ).each(function( index, element ) {
    // element == this
    $( element ).css( "backgroundColor", "yellow" );//element(div태그) 의 배경색이 yellow로 변경된다

    if ( $( this ).is( "#stop" ) ) {// 만약 #stop 이란 아이디값을 갖고있으면
      
      $( "span" ).text( "Stopped at div index #" + index );
      //span태그에 "Stopped at div index #"+index라고 입력되라 
      //(여기서 index값은 #stop이란 값을 갖고있는 div의 정수 = 4 )
      // 다섯번째 div에 stop아이디값이 들어있으므로 0, 1, 2, 3, 4 
	
      
      //그러므로 span태그에 "Stopped at div index #4" 라고 노출될 것이다.

      return false; //반복금지 (5번째까지만 노란색으로 div배경이 변경되고 나머지는 each()반복을 빠져나오므로 노란색으로 변경x)
    }
  });
});

See the Pen rpJaNa by seobin (@lullu-lalla) on CodePen.


'jquery test' 카테고리의 다른 글

[ skrollr | 스크롤 기반 애니메이션 > 모바일디바이스 이슈 ]  (0) 2018.01.17
eq().each() - type02  (0) 2018.01.09
.eq().each() - type01  (0) 2018.01.09
반응형 웹 메뉴바  (0) 2018.01.05
slide up / down  (0) 2018.01.04

관련글 더보기

댓글 영역