JQUERY/함수

each(), addClass(), toggleCalss()

나이많은 초보 2022. 8. 28. 18:37
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="../RESOURCES/asset/js/jquery-3.6.0.min.js"></script>
    <style>
        .high_light_0{background: red; color: white;}
        .high_light_1{background: orange; color: black;}
        .high_light_2{background: green; color: white;}
        .high_light_3{background: blue; color: white;}
        .high_light_4{background: purple; color: white;}
    </style>

</head>
<body>
    <h1>자체 제공 함수</h1>
    <h3>$.each()</h3>
    <p>
        $.each(객체(배열), function(index,item){. . .}); <br>
        index:배열에 해당하는 반복 순번, 특정 객체의 경우 해당 객체의 각 키들  <br>
        item: 해당 순번에 맞는 값
    </p>
    <div id="wrap1"></div>
    <script>
        var arr=[
            {name : '네이버',address : 'https://www.naver.com'},
            {name : '다음', address: 'https://www.daum.net'},
            {name : '구글', address : 'https://www.google.com'}
        ];
        $.each(arr,function(index,item){
            var outHTML = "";
            console.log(index + "/" + item);
            console.log(item);
            outHTML +='<a href="'+item.address+ '"target="_blank">';
            outHTML +='<span>'+item.name+'</span>';
            console.log(outHTML);
           
            //text()/ html()
            //text():  html요소를 배제하고 문자열만 저장하건, 가져오는 함수
            //html(): html요소를 태그로 올바르게 인식하는 함수

          //  $('#wrap1').text(outHTML);
            $('#wrap1').html($('#wrap1').html()+outHTML);
        });
    </script>

    <h3>$(선택자).each()함수</h3>
    <!--div#wrakp2>h1{item$}*5-->
    <div id="wrap2">
        <h1>item1</hq>
        <h1>item2</hq>
        <h1>item3</hq>
        <h1>item4</hq>
        <h1 id="sw">item5</hq>
    </div>
    <script>
        console.log($('#wrap2').children());
        $('#wrap2 h1').each(function(index,item){
            $(this).addClass('high_light_'+index);
            //addClass()<---> removeClass();
            //선택한 요소에 클래스값을 추가할수 있는 addClass.
        });
        $('#sw').click(function(){
            $(this).toggleClass('high_light_4');
            //toggleClass()로 선택한 요소에 클래스(Class) 값을 넣었다 뺐다 할 수 있습니다.
            //클릭할때 마다 넣다 뺏다 할수 있음
        });
    </script>



</body>