출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

each$.each( ) 메서드의 콜백 함수

each() > 하나의 행을 다루는 핸들러 / 함수

        $(document).ready(function() {
            // 배열의 반복 처리를 위한 each 메소드
            // $.each(배열의 원본, callbck : 하나의 행을 처리하는 함수)
            
            // 배열 생성
            var links = [
                {name:'네이버', url:'http://www.naver.com'},
                {name:'다음', url:'http://www.daum.net'},
                {name:'구글', url:'http://www.google.com'},
            ];
            
            var output='';
            
            $.each(links, function(index,item){
                console.log(index, item);
                
                output += '<h1><a href="'+item.url+'">'+item.name+'</a></h1>';
            })     
                document.body.innerHTML +=output;
           
            
        });

 

addclass() 메서드

 

        $(document).ready(function() {
            $('h1').addClass('title');

            $('h1').each(function(index, item) {
                if (index % 2 == 0) {
                    $(item).css('color', 'red');
                }
            });

        });
    </script>
    <style>
        .title {
            background-color: beige;
            font-style: italic;
        }
    </style>
</head>

<body>

    <h1> h1 - 1 </h1>
    <h1> h1 - 2 </h1>
    <h1> h1 - 3 </h1>
    <h1> h1 - 4 </h1>
    <h1> h1 - 5 </h1>

        $(document).ready(function() {
//            $('h1').addClass('title');

            $('h1').each(function(index, item) {
                if (index % 2 == 0) {
                    /*$(item).css('color', 'red');*/
                    $(item).addClass('title')
                }
            });

        });
    </script>
    <style>
        .title {
            background-color: beige;
            font-style: italic;
        }
    </style>
</head>

<body>

    <h1> h1 - 1 </h1>
    <h1> h1 - 2 </h1>
    <h1> h1 - 3 </h1>
    <h1> h1 - 4 </h1>
    <h1> h1 - 5 </h1>

+ Recent posts