JQUERY-This

임재헌·2023년 3월 31일

JQUERY

목록 보기
7/16
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>07_this_index.html</title>
  <script src="jquery-3.6.4.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="color">?</span></dd>
                <dd>클릭한 버튼의 글자 : <span id="text">?</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개의 댓글