웹개발 교육/jQuery

[42일] jQuery (7) - this

ewok 2022. 9. 26. 16:50

this를 사용할 때는 주의를 해서 사용해야 한다. 어떻게 쓰는냐에 따라 그 의미가 달라지기 때문이다.

$(this)     jQuery에서 this객체 접근
$("this")   본문에서 <this>요소에 접근 및 선택
$("<this>")   본문에 <this>요소 생성

 

 

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>07_this_index.html</title>
        <!-- jQuery import -->
        <script src="jquery-3.6.1.min.js"></script>
        <style>
            #exBox {width: 400px; height: 300px;}
            .btn {width: 120px; height: 50px; cursor: pointer;/*손모양커서*/}
            #pinkBtn {background: hotpink;}
            #blueBtn {background: blue;}
            #greenBtn {background: green;}
        </style>
    </head>  
    <body>

        <h3>클릭한 요소의 인덱스 얻기(index)</h3>
        <button>버튼1</button>
        <button>버튼2</button>
        <button>버튼3</button>
        <hr>
        
        <h3>this 연습</h3>
        <div id="exBox">
            <p>
                <button id="pinkBtn" class="btn">멋진 핑크</button>
                <button id="blueBtn" class="btn">쿨한 파랑</button>
                <button id="greenBtn" class="btn">네온 녹색</button>
            </p>
            <dl>
                <dt>클릭한 버튼정보</dt>
                    <dd>클릭한 버튼의 index : <span id="index">?</span></dd>
                    <dd>클릭한 버튼의 뒷배경색 : <span id="index">?</span></dd>
                    <dd>클릭한 버튼의 글자 : <span id="index">?</span></dd>
            </dl>
        </div>
        <script>
            //$(this)     jQuery에서 this객체 접근
            //$("this")   본문에서 <this>요소에 접근 및 선택
            //$("<this>")   본문에 <this>요소 생성

            $("button").click(function(){
                //this 선택한 요소 자신을 가리킴

                //1)JavaScript
                this.style.color="red";

                //2)jQuery
                //->자바스크립트 요소 객체 this를 jQuery객체 $(this)로 변경한 후 사용한다.
                //->this.css() 에러
                $(this).css("color", "blue");

                //사용자가 클릭한 요소의 인덱스 가져오기
                let idx = $(this).index();  //1부터 시작
                alert(idx);

            });//click end

            $("#exBox .btn").click(function(){
                let idx = $(this).index(); //0부터 시작
                //alert(idx);

                var color = $(this).css("background-color");
                var txt = $(this).text();
                //alert(color);
                //alert(txt);

                $("#index").text(idx);
                $("#color").text(color);
                $("#text").text(txt);


            }); //click end

        
        </script>
        
    </body>
</html>

인덱스는 0부터 시작한다. 버튼 1을 클릭해보면 인덱스로 1이 나오는데 부모 태그인 <body>로부터 2번째이기 때문이다.

멋진 핑크 버튼을 클릭하면 인덱스로 0이 나오는데 이것은 부모 태그인 <p>로부터 1번째이기 때문이다.

 

07_this_index.html

클릭한 요소의 인덱스 얻기(index)


this 연습

클릭한 버튼정보
클릭한 버튼의 index : ?
클릭한 버튼의 뒷배경색 : ?
클릭한 버튼의 글자 : ?