jQuery | javascript | CSS

10.jQuery - this 이벤트 ( 10.ThisId )

Godffs 2009. 11. 6. 10:24
반응형

$(this)  : 이벤트 핸들러 컨텍스트
 this : 이벤트 핸들러에서의 this는 DOM을 가리킨다.
 $(this) : 현재 이벤트가 적용된 개체(DOM)를 jQuery 개체로 반환한다.
 this.id : DOM 개체 중 클릭된 요소를 알고자 할 때에는 id 속성을 사용한다.

아이디 값에 따라서 각각의 이벤트를 주는 예제입니다.

10.ThisId.htm

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>this.id DOM 요소의 id 속성 가져오기</title>

    <style type="text/css">

        .redColor

        {

            color: Red;

        }

    </style>

    <script src="js/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            //[1] 닷넷코리아 레이어 클릭시 CSS 클래스 해제

            $('#dnk').bind('click', function() {

                //[a] 해제

                $('#mainMenu .redColor').removeClass('redColor'); //3개의 요소의 CSS 클래스 해제

                //[b] #dnk 다시 적용

                $(this).addClass('redColor'); // 현재 나만 다시 적용

            });

           

            //[2] mainMenu 모든 항목에 대해서 click 이벤트 적용

            $('#mainMenu .redColor').bind("click", function() {

                //[!] this.id 분기

            if (this.id == "Godffs") { alert("준철이 블로그"); }

               

                else if (this.id == "Gg")

                { alert($(this).text()); } // #Gg안에 들어 있는 텍스트

            });

        });

    </script>

</head>

<body>

    <div id="mainMenu">

        <div id="dnk" class="redColor">닷넷코리아</div>

           

        <div id="Godffs" class="redColor">준철이 블로그</div>

           

        <div id="Gg" class="redColor">구글</div>

    </div>

</body>

</html>


결과화면

[그림10-1]
10.ThisId.htm
반응형