미채택 완료

for 문

2020-04-14 (화) 16:26:12 3,268

 $( "div" ).each( function() {
         if ( $( 'li', this ).length == 2 ) {
             $( this ).addClass( 'item2' );
        } else if( $( 'li', this ).length == 3) {
             $( this ).addClass( 'item3' );
        }else if( $( 'li', this ).length == 4) {
             $( this ).addClass( 'item4' );
        }else if( $( 'li', this ).length == 5) {
             $( this ).addClass( 'item5' );
        }else if( $( 'li', this ).length == 6) {
             $( this ).addClass( 'item6' );
        }
});

위 코드 for문으로 10번 돌리는 법

답변 좀 부탁 드릴게요.....

|

답변 2개

 for문으로 10번 ??? 무엇을 하려는지 모르겠군요

div가 10개있으면 저절로 10번 실행될텐데요

그리고 저렇게 규칙적인 것은 한번만으로 될텐요

아래처럼 해보세요

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

 nn = $( 'li', this ).length; //<--이것은 무엇을 하려는 의도인가요? li의 갯수 라면 $(this).find('li').length; 

$( this ).addClass( 'item' +nn);

});

function divLoops() {

   $( "div" ).each( function() {
         if ( $( 'li', this ).length == 2 ) {
             $( this ).addClass( 'item2' );
        } else if( $( 'li', this ).length == 3) {
             $( this ).addClass( 'item3' );
        }else if( $( 'li', this ).length == 4) {
             $( this ).addClass( 'item4' );
        }else if( $( 'li', this ).length == 5) {
             $( this ).addClass( 'item5' );
        }else if( $( 'li', this ).length == 6) {
             $( this ).addClass( 'item6' );
        }
   });

}

for (var i = 0; i < 10; i++) {

    divLoops();

}

답변을 작성하려면 로그인이 필요합니다.