개발자의 길/jQuery
jQuery 반복문(each)
모쿠
2017. 4. 10. 17:05
<jQuery의 반복문 사용 : each() 함수>
- 홀수줄은 hotpink , 짝수줄은 aqua로 출력
- '컬렉션'.each(handler);
- handler: 컬렉션의 모든 원소들에 대해서 적용할 기능(동작)
<08_each.html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jQuery</title> <style> .hot { background-color: hotpink; } .cold{ background-color: aqua; } </style> </head> <body> <h1>jQuery each() 함수</h1> <ul> <li>Java</li> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>jQuery</li> </ul> <button type="button" id="btn">Toggle Style</button> <!-- jQuery CDN 포함: 라이브러리 포함 --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script> $(document).ready(function() { // '컬렉션'.each(handler); // handler: 컬렉션의 모든 원소들에 대해서 적용할 기능(동작) $('#btn').click(function() { var order = true; // each는 반복문(for문과 같음) $('li').each(function(index) { if(index % 2 == 0){ $(this).toggleClass('hot'); order = false; } else { $(this).toggleClass('cold'); order = true; } }); }); }); </script> </body> </html> | cs |
<출력화면>