본문 바로가기

Programming/국비학원

220707 - 자바스크립트 - DOM, 이벤트

  • ex. 버튼 클릭 시 숫자 누적

    <script>
        window.onload=function(){
            var btnA=document.getElementById('buttonA');
            var btnB=document.getElementById('buttonB');
            var cntA=document.getElementById('countA');
            var cntB=document.getElementById('countB');
            btnA.onclick=function(){
                cntA.innerHTML=Number(cntA.innerHTML)+1; 
            }
            btnB.onclick=function(){
                cntB.innerHTML=Number(cntB.innerHTML)+1;
                btnA.onclick();  //btnA와 동시에 숫자 누적
            }
        }
    </script>
</head>
<body>
    <button id="buttonA">김철수 투표</button>
    <button id="buttonB">이영희 투표</button>
    <h1>김철수-<span id="countA">0</span></h1>
    <h1>이영희-<span id="countB">0</span></h1>
</body>

 

 

  • 인라인 이벤트 모델 (△)
  •  

<body>
    <h1 onclick="alert('안녕하세요');">인사</h1>
</body>

 

 

  •  

<body>
    <h1 onclick="var age=25;alert('당신의 나이는'+age+'입니다');">나이는?</h1>
</body>

 

 

 

이벤트 제거
  • 디폴트 이벤트 취소

: html 태그에 내재된 이벤트 (ex. type='submit'인 태그는 다른 서버에 내용 제출하는 이벤트 내장) 동작 취소 

 

 

  •  

    <script>
        window.onload=function(){
            var br=document.getElementById('br');
            br.onclick=function(){
                return false;  // 기존 이벤트 삭제
            }
        }
    </script>
</head>
<body>
    <a href="http://www.kbs.co.kr" id="br">한국 방송</a>
</body>

 

 

  • 회원가입창 - submit 이벤트 취소

    <script>
        window.onload=function(){
            var myForm=document.getElementById('myForm');
            myForm.onsubmit=function(){
                var pass=document.getElementById('pass').value;
                //input 입력값 전달
                var passC=document.getElementById('passC').value;
                if (pass==passC){
                    alert('성공');
                }else{
                    alert('다시 입력해주세요');
                    return false;  //submit 이벤트 취소
                }
            }
        }
    </script>
</head>
<body>
    <form action="member.jsp" method="post" id="myForm">
        <p>
            <label for="id">아이디</label>
            <input type="text" id="id" name="id" required>
        </p>
        <p>
            <label for="pass">비밀번호</label>
            <input type="password" id="pass" name="pass" required>
        </p>
        <p>
            <label for="passC">비밀번호 확인</label>
            <input type="password" id="passC" name="passC" required>
        </p>
        <input type="submit" value="회원가입">
    </form>
</body>

 

 

  • 문제 : 

1. 작은이미지 클릭 -> 상단 큰 이미지에 해당 이미지 표시
2. 상세설명보기 클릭 -> 상세 설명 visible,  상세설명닫기로 글자 변화

 

 

    <script>
        window.onload=function(){
            var bigPic=document.querySelector('#prodPic > img');
            var smallPic=document.querySelectorAll('#smallPic > img');
            //3개 이미지 => selectorall (배열로 저장)
            for (var i=0;i<3;i++){
                smallPic[i].onclick=function(){
                    bigPic.src=this.src;
                }
            }

            var view=document.querySelector('#view');
            var detail=document.querySelector('#detail');
            var isOpen=false;

            view.onclick=function(){
                isOpen=!isOpen;
                if (isOpen){
                    detail.style.display='inline-block';
                    this.innerText="상세 설명 닫기";  //innerText : 태그 인식 X
                }else{
                    detail.style.display='none';
                    this.innerHTML="상세 설명 보기";
                }
            }
        }
    </script>

</head>
<body>
    <div id="container">
        <h1 id="heading">에티오피아 게뎁</h1>
        <div id="prodPic">
            <img src="../images/coffee-pink.jpg" alt="게뎁">
            <div id="smallPic">
                <img src="../images/coffee-pink.jpg" alt="핑크컵">
                <img src="../images/coffee-blue.jpg" alt="블루컵">
                <img src="../images/coffee-gray.jpg" alt="그레이컵">
            </div>
        </div>
        <div id="desc">
            <ul>
                <li>상품명 : 에티오피아 게뎁</li>
                <li class="bluetext">판매가 : 9,000원</li>
                <li>배송비 : 3,000원<br>(50,000원 이상 구매시 무료)</li>
                <li>적립금 : 180원 (2%)</li>
                <li>로스팅 : 2022-07-02</li>
                <button>장바구니 담기</button>
            </ul>
            <a href="#" id="view">상세 설명 보기</a>
        </div>
        <div id="detail">
            <hr> <!--수평 선-->
            <h2>상품 상세 정보</h2>
            <ul>
                <li>원산지 : 에티오피아</li>
                <li>지역 : 이르가체프 코체레</li>
                <li>농장 : 게뎀</li>
                <li>고도 : 1950~2000m</li>
                <li>품종 : 지역 토착종</li>
                <li>가공법 : 워시드</li>
            </ul>
            <h3>Information</h3>
            <p>2차 세계대전 이후 설립된 게뎀 농장은 유기농 인증 농장으로
                여성의 고용창출과 지역사회 발전에 기여하며 3대째 이어져
                내려오는 오랜 역사를 가진 농장입니다.
            </p>
            <h3>Flavor Note</h3>
            <p>은은하고 다채로운 꽃향, 망고, 다크체리, 달달함이 입안 가득</p>
        </div>
    </div>
</body>

 

 

  • 문제 : 불렛 클릭 -> 해당 줄 전체 회색 변환 + default cursor 

 

    <style>
        ul{
            list-style: none;
        }
        li{
            font-size: 1.5em;
            line-height: 1.8;
        }
        .check{
            color: #ccc;
            cursor: pointer;  /*기본: default*/
            font-size: 1.5em;
            margin-right: 25px;
        }
        .check:hover{
            color: black;
        }
    </style>

</head>
<body>
    <h1>할일 목록</h1>
    <ul>
        <li><span class="check">&check;</span>집안 청소하기</li>
        <li><span class="check">&check;</span>홈페이지 제작</li>
        <li><span class="check">&check;</span>밀린 빨래하기</li>
        <li><span class="check">&check;</span>운동하기</li>
        <li><span class="check">&check;</span>반찬 만들기</li>
    </ul>
</body>

 

 

=>

 

1. 

    <script>
        window.onload=function(){
            var check=document.querySelectorAll('.check');
            for (var i=0;i<check.length;i++){
                check[i].addEventListener('click',function(){
                    this.style.color='#ccc';
                    this.style.cursor='default';
                    this.parentNode.style.color='#ccc';
                    this.parentNode.style.cursor='default'; 
                });
            }


            /* 내 답변 (실패)
            var check=document.querySelectorAll('.check');            
            var list=document.querySelectorAll('li');
            for (var i=0;i<check.length;i++){
                check[i].onclick=function(){
                    this.style.color='#ccc';
                    this.style.cursor='default';
                    list[i].style.color='blue';  ///?
                    list[i].style.cursor='default';  ///?
                }
            }*/

            /* 예시답변 2
            var check=document.querySelectorAll('.check');            
            var list=document.querySelectorAll('li');
            for (var i=0;i<check.length;i++){
                check[i].onclick=function(){
                    this.style.color='#ccc';
                    this.style.cursor='default';
                }

                list[i].addEventListener('click',function(){
                    this.style.color='#ccc';
                    this.style.cursor='default';
                });
            */
        }
    </script>

 

2. 이벤트 제거 기능 추가

 

 <script>
        window.onload=function(){
            var check=document.querySelectorAll('.check');            
            var list=document.querySelectorAll('li');
            for (var i=0;i<check.length;i++){
                check[i].onclick=function(){
                    this.style.color='#ccc';
                    this.style.cursor='default';
                }

                list[i].addEventListener('click',job);

                function job(){
                    this.style.color='#ccc';  //this는 list[i]
                    alert('임무 완료');
                    this.removeEventListener('click',job);  //this[i]의 이벤트 완전 삭제
                }
            }
        }
    </script>

 

 

  • 이벤트 삭제 (removeEventListener)
  • ex. 1회 실행 후 이벤트 제거

    <script>
        window.onload=function(){
            var h=document.querySelector('#head');
            //h.onclick=function(){}
            //h.addEventListener('click',function(){})
            h.addEventListener('click',hello);
            //hello 뒤 괄호 붙이지 X 유의
        }

        function hello(){
            alert('안녕');
            this.style.cursor='default';
            this.style.color='#ccc';
            this.removeEventListener('click',hello);
            //한번 클릭하면 이벤트 삭제
        }
    </script>
</head>
<body>
    <h1 id="head">인사하기</h1>
</body>

 

 

  • ex. 폼 관련 이벤트 처리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        ul{
            list-style: none;
        }
        legend{
            font-size: 1.2em;
            font-weight: bold;
            margin-left: 20px;
        }
        form{
            width: 520px;
            height: auto;
            padding-left: 10px;
            margin: 50px auto;
        }
        fieldset{
            border: 1px solid #ccc;
            padding: 30px 20px 30px 30px;
            margin-bottom: 35px;
        }
        .field{
            float: left;
            width: 60px;
            font-weight: bold;
            font-size: 0.9em;
            line-height: 55px;
            text-align: right;
            margin-right: 15px;
        }
        .input-box{
            width: 350px;
            height: 35px;
            border: 1px solid #ccc;
            padding: 5px;
            margin: 10px 0;
            float: left;
            border-radius: 5px;
        }
    </style>
    <script>
        window.onload=function(){
            var check=document.querySelector('#shippingInfo');
            check.addEventListener('click',function(){
                if (this.checked==true){
                    document.querySelector('#shippingName').value=document.querySelector('#billingName').value;
                    document.querySelector('#shippingTel').value=document.querySelector('#billingTel').value;
                    document.querySelector('#shippingAddr').value=document.querySelector('#billingAddr').value;
                } else {
                    document.querySelector('#shippingName').value='';
                    document.querySelector('#shippingTel').value='';
                    document.querySelector('#shippingAddr').value='';                
                }
            });
        }
    </script>
</head>
<body>
    <div id="container">
        <form action="" name="order">
            <fieldset>
                <legend>주문 정보</legend>
                <ul>
                    <li>
                        <label class="field" for="billingName">이름 : </label>
                        <input type="text" class="input-box" id="billingName" name="billingName">
                    </li>
                    <li>
                        <label class="field" for="billingTel">연락처 : </label>
                        <input type="text" class="input-box" id="billingTel" name="billingTel">
                    </li>
                    <li>
                        <label class="field" for="billingAddr">주소 : </label>
                        <input type="text" class="input-box" id="billingAddr" name="billingAddr">
                    </li>
                </ul>
            </fieldset>
        </form>
        <form action="" name="ship">
            <fieldset>
                <legend>배송 정보</legend>
                <ul>
                    <li>
                        <input type="checkbox" id="shippingInfo" name="shippingInfo">
                        <label for="shippingInfo" class="check">주문 정보와 배송 정보가 일치합니다</label>
                    </li>
                    <li>
                        <label class="field" for="shippingName">이름 : </label>
                        <input type="text" class="input-box" id="shippingName" name="shippingName">
                    </li>
                    <li>
                        <label class="field" for="shippingTel">연락처 : </label>
                        <input type="text" class="input-box" id="shippingTel" name="shippingTel">
                    </li>
                    <li>
                        <label class="field" for="shippingAddr">주소 : </label>
                        <input type="text" class="input-box" id="shippingAddr" name="shippingAddr">
                    </li>                 
                </ul>
            </fieldset>
        </form>
    </div>
</body>
cs

 

※ input 기본 => inline-block