반응형
■ jQuery를 사용한 배열 관리
-. jQuery를 사용해 배열을 관리할 때는 each() 메서드를 사용
-. each() 메서드는 매개 변수로 입력한 함수를 사용해 for in 반복분처럼 객체나 배열의 요소를 검사하는 메서드 이다.
-. each() 메서드는 다음과 같이 두 가지 형태를 갖는다.
① $.each(object, function(index, item) { })
② $(selector).each(function(index, item) { })
01. 자바스크립트의 배열을 $.each() 메서드를 사용해 다루는 방법
jQueryArray01.html |
<!DOCTYPE html> <html> <head> <title> jQuery를 사용한 배열 관리 </title> <script src="http://code.jquery.com/jquery-1.7.js"></script> <script> $(document).ready(function () { // 변수를 선언한다. var array = [ { name : 'Google', link : 'http://ww.google.co.kr' }, { name : 'Naver', link : 'http://www.naver.com' }, { name : 'Daum', link : 'http://ww.daum.net' }, { name : 'Nate', link : 'http://www.nate.com/' } ]; // $.each() 메서드를 사용한다. $.each(array, function (index, item) { // index는 배열의 인덱스 또는 객체의 키를 의미 // item은 해당 인덱스나 키가 가진 값을 의미 // 변수를 선언한다. var output = ''; // 문자열을 만든다. output += '<a href="' + item.link + '">'; output += ' <h1>' + item.name + '</h1>'; output += '</a>'; // body 태그의 뒷부분에 집어넣는다. document.body.innerHTML += output; }); }); </script> </head> <body> </body> </html> |
출력결과 |
02. jQuery의 배열 객체를 다루는 방법
-. jQuery의 배열 객체는 따로 만드는 것이 아니라 선택자를 사용해 여러 개의 문서 객체를 선택 할 때 생성
jQueryArray02.html |
<!DOCTYPE html> <html> <head> <title> jQuery를 사용한 배열 관리 </title> <style> .high_light_0 { background:Yellow; } .high_light_1 { background:Orange; } .high_light_2 { background:Blue; } .high_light_3 { background:Green; } .high_light_4 { background:Red; } </style> <script src="http://code.jquery.com/jquery-1.7.js"></script> <script> $(document).ready(function () { $('h1').each(function (index, item) { $(this).addClass('high_light_' + index); }); }); </script> </head> <body> <h1>item - 0</h1> <h1>item - 1</h1> <h1>item - 2</h1> <h1>item - 3</h1> <h1>item - 4</h1> </body> </html> |
출력결과 |
반응형
'jQuery' 카테고리의 다른 글
[jQuery] 페이지 로드 전에 jQuery / 자바스크립트 실행하기 (0) | 2015.04.21 |
---|---|
[jQuery] jQuery를 사용한 객체 확장 (0) | 2013.09.10 |
[jQuery] jQuery 문법 (0) | 2013.02.22 |
[jQuery] jQuery 라이브러리 사용하기 (0) | 2013.02.22 |
[jQuery] CDN(Content Delivery Network) 호스트 (0) | 2013.02.22 |