자바스크립트 정리(2)

조이연·2023년 1월 3일
0

JSP

목록 보기
6/19

<keyup이벤트>

  <script>


        $(document).ready(function() {
            $('#msg').on('keyup', function(e) {
                // $('#target').text($('msg').val());   // -> msg == e.target
                $('#target').text(e.target.value);
            });

            $('button').on('click', function(e) {
                console.log(e.target);
            })
        });
    </script>
</head>
<body>
    <input type="text" id="msg"/>
    <span id="target"></span>
    <hr>
    <button>aaa</button>
    <button>bbb</button>
    <button>ccc</button>
</body>
  • 이벤트가 발생했을 때 그 이벤트를 잡아내는 역할을 누가 한다? 시스템
    시스템이 이벤트 정보를 담은 객체를 생성한다 -> 이벤트 객체 -> 이벤트 핸들러의 매개변수
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>이벤트 객체에서 주의할 점</title>
    <script>
        $(document).ready(function() {
            $('#btn').on('click', function(e) {
                // e.target은 html
                console.log(e.target);
                // e.target.text is not a function
                const $target = $(e.target);
                $target.text('클릭했어요');
                $('<strong>').text('까꿍').css('color','red').appendTo($('#target'));
            })
        })
    </script>
</head>
<body>
    <input type="text" id="msg">
    <button id="btn">클릭하세요</button>
    <div id="target">
        
    </div>
</body>
</html>
  • .appendTo(): 선택한 요소를 다른 요소 안에 넣습니다.
<style>
        #canvas { width: 400px; height: 400px; background-color: red;}
    </style>
    <script>
        // #canvas를 클릭하면 마우스 좌표를 출력하시오
        // 1. 이벤트 정보는 이벤트 객체에 들었다
        // 2. 좌표는 pageX, pageY -> alert로 출력하시오
        $(document).ready(function() {
            $('#canvas').on('click', function(e) {
                alert(`마우스 X좌표: ${e.pageX}, Y좌표: ${e.pageY}`);
            })

            // 마우스를 이동하면 #pos에 마우스 좌표를 출력하시오
            $('#canvas').on('mousemove', function(e) {
                $('#pos').text(`마우스 X좌표:${e.pageX}, Y좌표:${e.pageY}`);
            })
        })
    </script>
</head>
<body>
    <div id="canvas"> <!--빨간 박스-->
    </div>
    <p id="pos"></p> <!--아래 글씨-->
</body>

결과:

<script>
        $(document).ready(function(){
            let count = 0;
            $('#inc').on('click', function () {
                count++;
                $('#count').text(count);
            });
            $('#dec').on('click', function() {
                count--;
                $('#count').text(count);
            });
        })
    </script>
</head>
<body>
    
    <button id="inc">+</button>
    <span id="count"></span>
    <button id="dec">-</button>
</body>

<use strict버전>

<script>
        'use strict'    //오류를 잡을 수 있다
        let count = 0;

        function inc() {
            count++;
            $('#count').text(count);
        }
        function dec() {
            count--;
            $('#count').text(count);
        }

        $(document).ready(function(){
            $('#inc').on('click', inc);
            $('#dec').on('click', dec);
        })
    </script>

<물건 구매하기>

<script>
        const product = { name: '우유', price: 2000, stock: 10 };
        // +를 누르면 개수가 증가, 구매예정금액 증가
        //  개수가 stock보다 커지면 '더 이상 구입할 수 없습니다'
        // -를 누르면 개수 감소, 구매예정금액 감소
        // 개수의 최소값은 1
        let count = 0;
        let money = 0;

        function show() {
            money = product.price * count;
            $('#count').text(count);
            $('#money').text(money);
        }

        /*
        function inc() {
            if(count<product.stock) {
                count++;
                money += 2000;
                $('#count').text(count);
                $('#money').text(money);
            } else {
                alert('더 이상 구입할 수 없습니다');
            }
        }
        function dec() {
            if(count>1) {
                count--;
                money -= 2000;
                $('#count').text(count);
                $('#money').text(money);
            }
        }
        */

        $(document).ready(function() {
            // $('#inc').on('click', inc);
            // $('#dec').on('click', dec);
            
            $('button').on('click', function(e) {
                const $btn = $(e.target);
                if($btn.text()==="+") {
                    if(count>=product.stock) {
                        alert('더 이상 주문할 수 없습니다');
                        return;
                    }
                    count++;
                    show();
                } else if ($btn.text()==="-") {
                    if(count<=1)
                        return;
                    count--;
                    show();
                }
            })
        })
    </script>
</head>
<body>
    <div id="name"></div>
    <div>
        <button id="inc">+</button>
        <span id="count"></span>
        <button id="dec">-</button>
    </div>
    <div>
        구매예정금액:<span id="money"></span>
    </div>
</body>
</html>

결과:

<데이터 여러개 처리하기>

 <title>데이터 여러개 처리하기</title>
    <script>
        // 사용자가 어떤 동작(이벤트) -> 처리 : 이벤트 driven(구동) 방식
        // 프로그래머는 이벤트를 처리하는 함수를 작성(이벤트 핸들러) -> 이벤트 소스에 함수를 등록
        // 자바스크립트는 이벤트 정보를 담은 객체를 생성하고 이벤트 핸들러를 불러준다
        // 프로그래머가 작성하고 위탁 실행하는 함수 -> 콜백(callback) 함수

        $(document).ready(function() {
            $('.delete').on('click', function(e) {
                const $btn = $(e.target);
                alert($btn.data('no'));
                alert($btn.attr('data-no'));
            })
        })
    </script>
</head>
<body>
    <div>
        <div>우리나라 좋은나라<button class="delete" data-no="4">삭제</button></div>
        <div>우리나라 좋은나라<button class="delete" data-no="3">삭제</button></div>
        <div>우리나라 좋은나라<button class="delete" data-no="2">삭제</button></div>
        <div>우리나라 좋은나라<button class="delete" data-no="1">삭제</button></div>
    </div>
</body>
</html>

<jQuery 반복문>

 <script>
        const carts = [
            {no:122, name:'신라면', price:4100},
            {no:357, name:'페레로로쉐 5T', price:3500},
            {no:1113, name:'오레오', price:1200}
        ];

        // ES6 of 반복문 -> 파일업로드
        for(cart of carts)
            console.log(cart);

        // jQuery 반복문
        // $.each(배열, function(인덱스, 원소))
        $.each(carts, function(index, cart) {
            console.log(cart);
        });
    </script>
  • $.each(배열, function(인덱스, 원소))
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <title>Document</title>
    <script>
        const carts = [
            {no:122, name:'신라면', price:4100},
            {no:357, name:'페레로로쉐 5T', price:3500},
            {no:1113, name:'오레오', price:1200}
        ];
        $(document).ready(function() {
            const $tbody = $('#tbody');
            $.each(carts, function(i, c) {
                const str = `
                    <tr>
                        <td>${c.no}</td>    
                        <td>${c.name}</td>
                        <td>${c.price}원</td>
                        <td><button class="delete" data-on=${c.no}>삭제</button></td>
                    </tr>
                `;
                $tbody.append(str);
            });
            $('.delete').on('click', function(e) {
                const $btn = $(e.target);
                console.log($btn.attr('data-no'));
                console.log($btn.parent().prev().prev().prev().text());
            })
        })
    </script>
</head>
<body>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>번호</th>
                <th>이름</th>
                <th>가격</th>
                <th>삭제</th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</body>
</html>
  • tbody 태그: HTML 테이블에서 내용 콘텐츠(body content)들을 하나의 그룹으로 묶을 때 사용합니다.

  • .table-hover 클래스: 추가하면 테이블에 마우스를 올렸을 때 마우스 커서가 있는 행이 다른 색으로 변합니다.(=mouseover)

  • thead 태그: HTML 테이블에서 헤더 콘텐츠(header content)들을 하나의 그룹으로 묶을 때 사용합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <title>Document</title>
    <script>
        const carts = [
            {no:122, name:'신라면', price:4100},
            {no:357, name:'페레로로쉐 5T', price:3500},
            {no:1113, name:'오레오', price:1200}
        ];
        $(document).ready(function() {
            const $tbody = $('#tbody');
            $.each(carts, function(i, c) {
                const str = `
                    <tr>
                        <td>${c.no}</td>    
                        <td>${c.name}</td>
                        <td>${c.price}원</td>
                        <td><button class="delete" data-on=${c.no}>삭제</button></td>
                    </tr>
                `;
                $tbody.append(str);
            });
            $('.delete').on('click', function(e) {
                const $btn = $(e.target);
                console.log($btn.attr('data-no'));
                console.log($btn.parent().prev().prev().prev().text());
            })
        })
    </script>
</head>
<body>
    <table class="table table-hover">
        <thead>
            <tr>
                <th>번호</th>
                <th>이름</th>
                <th>가격</th>
                <th>삭제</th>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</body>
</html>

<append태그>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>이벤트 처리하기</title>
    <script>
        $(document).ready(function() {
            $('#append').on('click', function() {
                // append는 마지막에 추가
                $('#target').append(`<li>동적으로 추가된 놈</li>`);
            }); //target에 append 이용해서 이 문구 추가하겠다구

            // 동적으로 추가된 요소는 이벤트가 동작하지 않는다(ready이벤트는 동적요소로 취급 x)
            /*
            $('li').on('click', function() {
                alert('클릭했어요');
            });
            */
            $('#target').on('click', 'li', function() {
                alert('클릭했어요');
            })
            
        })
    </script>
</head>
<body>
    <button id="append">li 추가</button>
    <ul id="target">
        <li>원래 있던 놈</li>
        <li>원래 있던 놈</li>
    </ul>
</body>
</html>
  • .append() :선택된 요소의 마지막에 새로운 요소나 콘텐츠를 추가한다.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>Document</title>
    <script>
        const carts=[
            {no:122, name:'신라면', price:4100, count:1, total:4100},
            {no:357, name:'페레로로쉐 5T', price:3500, count:1, total:3500},
            {no:1113, name:'오레오', price:1200, count:1, total:1200}
        ];

        function printCarts($tbody) {
            $tbody.empty();
            $.each(carts, function(i, c) {
                const str = `
                    <tr>
                        <td>${c.name}</td>
                        <td>
                            <button data-no=${c.no} class="inc">+</button>
                            ${c.count}
                            <button data-no=${c.no} class="dec">-</button>
                        </td>
                        <td>
                            ${c.total}
                        </td>
                    </tr>
                `;
                $tbody.append(str);
            })
        }

        $(document).ready(function() {
            const $tbody = $('#tbody');
            printCarts($tbody);
            $('#tbody').on('click', '.inc', function(e) {
                const $incBtn = $(e.target);
                const no = parseInt($incBtn.attr('data-no'));
                for(cart of carts) {
                    if(cart.no===no) {
                        cart.count++;
                        cart.total = cart.count * cart.price;
                        printCarts($tbody);
                    }
                }
            })
        })
    </script>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>이름</th>
                <th>개수</th>
                <th>구매가격</th>
            </tr>
        </thead>
        <tbody id="tbody">
            
        </tbody>
    </table>
</body>
</html>
profile
안녕하세요

0개의 댓글