.each()

· 2017-09-05 (화) 23:55:56 · 1746

.each()


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


.each()방법은 DOM 루핑 구조를 간결하고 오류를 발생시키지 않는 구조로 설계되었습니다. 그것을 호출하면 jQuery 객체의 일부인 DOM 요소를 반복합니다. 콜백이 실행될 때마다 0부터 시작하는 현재 루프 반복이 전달됩니다. 더 중요한 것은 콜백은 현재 DOM 요소의 컨텍스트에서 발생하므로 키워드 this는 요소를 참조합니다.


페이지에 단순한 정렬되지 않은 목록이 있다고 가정합니다.


<ul>

  <li>foo</li>

  <li>bar</li>

</ul>

목록 항목을 선택하고 항목을 반복 할 수 있습니다.


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

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

});

따라서 메시지는 목록의 각 항목에 대해 기록됩니다.


0 : foo 

1 : 바


돌아 오는 방법으로 콜백 함수 내에서 루프를 멈출 수 있습니다 false.


참고 : jQuery 객체를 반환하는 대부분의 jQuery 메서드는 jQuery 컬렉션의 요소 집합을 반복 합니다. 이는 암시 적 반복 이라고하는 프로세스 입니다. 이 문제가 발생 하면 메서드를 사용 하여 명시 적으로 반복 할 필요가없는 경우가 있습니다 .each().


// The .each() method is unnecessary here:

$( "li" ).each(function() {

  $( this ).addClass( "foo" );

});

 

// Instead, you should rely on implicit iteration:

$( "li" ).addClass( "bar" );


예)

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>each demo</title>

  <style>

  div {

    color: red;

    text-align: center;

    cursor: pointer;

    font-weight: bolder;

    width: 300px;

  }

  </style>

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

 

<div>Click here</div>

<div>to iterate through</div>

<div>these divs.</div>

 

<script>

$( document.body ).click(function() {

  $( "div" ).each(function( i ) {

    if ( this.style.color !== "blue" ) {

      this.style.color = "blue";

    } else {

      this.style.color = "";

    }

  });

});

</script>

 

</body>

</html>

|
댓글을 작성하시려면 로그인이 필요합니다.

개발자팁

5,403건

개발과 관련된 유용한 정보를 공유하세요. 질문은 QA에서 해주시기 바랍니다.

+
분류 제목 글쓴이 날짜 조회
jQuery
[jQuery]
17-09-09 조회 1,863
jQuery 17-09-09 조회 2,684
jQuery 17-09-09 조회 4,079
PHP 17-09-08 조회 6,131
기타 17-09-08 조회 2,419
기타 17-09-08 조회 2,236
기타 17-09-08 조회 2,529
jQuery 17-09-07 조회 2,138
jQuery 17-09-07 조회 1,849
jQuery 17-09-07 조회 2,642
jQuery 17-09-06 조회 2,331
jQuery
[jQuery]
17-09-06 조회 2,088
jQuery 17-09-06 조회 2,375
jQuery
[jQuery]
17-09-05 조회 1,776
jQuery
[jQuery]
17-09-05 조회 2,056
jQuery
[jQuery]
17-09-05 조회 1,747
jQuery
[jQuery]
17-09-02 조회 1,684
jQuery 17-09-02 조회 1,991
jQuery 17-09-02 조회 2,094
jQuery 17-09-01 조회 2,088
jQuery 17-09-01 조회 2,234
jQuery 17-09-01 조회 1,971
jQuery 17-08-31 조회 2,328
jQuery 17-08-31 조회 2,440
jQuery 17-08-31 조회 1,873
PHP 17-08-31 조회 3,291
jQuery 17-08-29 조회 1,876
jQuery 17-08-29 조회 2,061
jQuery 17-08-29 조회 2,142
jQuery 17-08-27 조회 2,003