기록/자바_국비

[배운내용정리] 0125 자바 국비교육_ Javascript_jQuery

mois 2021. 2. 7. 04:54
728x90

2021년 01월 25일 9시 ~ 15시 30분 zoom으로 수업 진행

 


 

자바스크립트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>주소록</title>

    <script type="text/javascript">
        function tableVal() {
            //form 요소를 모두 반환해주는 친구
            var doc = document.forms[0];
            var vals = [doc.id.value, doc.pw.value, doc.addr.value, doc.phone.value];

            console.log(doc);
            console.log(vals);

            //유효값 처리
            for(var i=0; i<vals.length; ++i) {
                if(vals[i] == null || vals[i] == "" || vals[i] == undefined) {
                    alert("모두 다 입력해주세요");
                    return;
                }
            }

            document.getElementById("addtr").appendChild(createRow(vals));
        }

        function createRow(vals) {
            var tr = document.createElement("tr");
            for(var i=0; i<vals.length; ++i) {
                var td = document.createElement("td");
                td.textContent = vals[i];
                tr.appendChild(td);
            }

            var dtd = document.createElement("td");
            dtd.innerHTML = "<input type='button' value='삭제' onclick='delRow(this);'>";
            tr.appendChild(dtd);

            return tr;

        }

        function deleteVal() {
            var tbody = document.getElementById("addtr");
            tbody.removeChild(tbody.lastChild);
        }

        function delRow(ele) {
            console.log(ele);
            //parentNode : 부모노드 탐색

            var delTr = ele.parentNode.parentNode;
            console.log(delTr);

            document.getElementById("addtr").removeChild(delTr);


        }
    </script>

</head>
<body>
    <form>
        <table id="intable">
            <tr>
                <td>ID</td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td>PW</td>
                <td><input type="text" name="pw"></td>
            </tr>
            <tr>
                <td>ADDR</td>
                <td><input type="text" name="addr"></td>
            </tr>
            <tr>
                <td>PHONE</td>
                <td><input type="text" name="phone"></td>
            </tr>
        </table>
        <input type="button" value="추가" onclick="tableVal();">
        <input type="button" value="삭제" onclick="deleteVal();">
    </form>

    <br><hr><br>

    <div id="addtable">
        <table border="1" id="ctb">
            <col width="100" />
            <col width="100" />
            <col width="300" />
            <col width="100" />
            <col width="100" />

            <thead>
                <tr>
                    <th>ID</th>
                    <th>PW</th>
                    <th>ADDR</th>
                    <th>PHONE</th>
                    <th>DELETE</th>
                </tr>
            </thead>
            <tbody id="addtr">

            </tbody>
        </table>

    </div>
</body>
</html>

 


 

자바스크립트 이벤트 버블링

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        .div-test {
            border: 1px solid black;
            padding: 20px;
        }
        .div1 {
            background-color: coral;
        }
        .div2 {
            background-color: yellowgreen;
        }
        .div3 {
            background-color: cornflowerblue;
        }
        .div4 {
            background-color: rebeccapurple;
        }
    </style>

    <script type="text/javascript">
        function test1(msg) {
            alert(msg);
        }
        function test2(msg,e) {
            var event = e || window.event;
            alert(msg);
            event.stopPropagation();
        }
    </script>
</head>
<body>
    <h3>
        이벤트 버블링
    </h3>

    <div onclick="test1('1번 div');" class="div-test div1">
        <div onclick="test1('2번 div');" class="div-test div2">
            <div onclick="test1('3번 div');" class="div-test div3">
                <div onclick="test1('4번 div');" class="div-test div4">

                </div>
            </div>
        </div>
    </div>

    <br><hr><br>

    <h3>
        이벤트 버블링 막기
    </h3>

    <div onclick="test2('1번 div');" class="div-test div1">
        <div onclick="test2('2번 div');" class="div-test div2">
            <div onclick="test2('3번 div');" class="div-test div3">
                <div onclick="test2('4번 div');" class="div-test div4">

                </div>
            </div>
        </div>
    </div>

    <h3> 표준 이벤트 모델 </h3>
    <button id="btn">확인</button>
    <script>
        window.onload = function() {
            var btn = document.getElementById("btn");

            btn.addEventListener('click', function(){
                alert('click 이벤트 발생');
            });

            btn.addEventListener('mouseenter', function(){
                alert('mouseenter 이벤트 발생');
            });
        }
    </script>
</body>
</html>

 


 

jQuery 시작

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        img {
            width: 200px;
            height: 200px;
            background-color: lightblue;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.5.1.js"></script>
    <script type="text/javascript">
    /*
        //페이지 내의 코드를 모두 읽어들인 후 실행해라 ==> window.onload = function() {}
        jQuery(document).ready(function() {
            //코드
        });

        jQuery 기본 작성법 : selector 표현식
        (css 작성법 + javascript 작성법)
        예)
            $("selector").함수();
            $("p").css("color", "red");

    */
        function highlight() {
            //id가 list01인 태그의 자식인 li를 찾아서
            //li들 중 첫번째 요소의 배경색을 pink로 변경

            /*
            //자바스크립트
            var li = document.getElementsByTagName("li")[0];
            console.log(li);
            li.style.backgroundColor="pink";
            */

            //제이쿼리 사용할 때 
            $("#list01 > li").eq(0).css("backgroundColor", "pink");
            //eq() : 선택한 요소의 인덱스 번호에 해당하는 요소를 찾는다.

        }

        $(function() {
            alert("로드완료");
            $("img").click(function() {
                //페이지가 로드되고 img 태그를 클릭했을 경우 실행되는 코드 작성하는 부분
                alert("이미지클릭");
                //$(this).hide();

            });
        });

        function showImage() {
            $("img").show();
        }

        function resizeImg() {
            //방법 1
            //$("img").css("width","100px").css("height","100px");
            //방법2
            $("img").css({"width":"100px", "height":"100px"});
        }

        function addImg() {
            $("img").last().after("<img src='image/pkinJin.png'>");
        }

        function toggleImg() {
            //이미지가 보이는 상태면 안 보이게, 안 보이는 상태면 보이게 해준다.
            $("img").toggle();
        }
        
    </script>
</head>
<body>
    <h1>
        JQuery 시작
    </h1>
    <ul id="list01">
        <li>1. 셀렉터 표현식</li>
        <li>2. DOM 탐색</li>
        <li>3. 이벤트 </li>
        <li>4. 이펙트</li>
        <li>5. Ajax</li>
    </ul>
    
    <button onclick="highlight();">리스트 강조하기</button>
    <hr>
    <button onclick="showImage();">이미지 보이기</button>
    <button onclick="resizeImg();">이미지 축소</button>
    <button onclick="addImg();">이미지 추가</button>
    <button onclick="toggleImg();">이미지 숨기기/보이기</button>
    <br><br>
    <div>
        <img alt="test" src="image/jin1.png">
    </div>
</body>
</html>

 


 

자바스크립트 표현식

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <!--아까 그 파일 경로 적거나 이거 적거나~!-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $("document").ready(function(){
            //div:eq(0) : ':' => 필터셀렉터, div 태그들 중에서 해당하는 index의 요소를 가져온다.
            $("div:eq(0)").css({"border":"1px solid red", "width" : "400px", "height":"200px", "margin-bottom" : "20px"});
            $("#view").css({"border":"1px solid blue", "width" : "400px", "height":"200px"});
        });

        function a1() {
            $("span").css("color", "red");
            $("#view").text('$("span").css("color", "red");');
        }

        function a2() {
            jQuery("#t1").css("color", "blue");
            jQuery("#view").text('jQuery("#t1").css("color", "blue");');
        }

        function a3() {
            $(".t2").css("color", "hotpink");
            $("#view").text('$(".t2").css("color", "hotpink");');
        }

        function a4() {
            $("li span").css("color", "mediumslateblue");
            $("#view").text('$("li span").css("color", "mediumslateblue");');
        }

        function a5() {
            $("li > span").css("color", "skyblue");
            $("#view").text('$("li > span").css("color", "skyblue");');
        }

        function a6() {
            //nth-child(n); 형제 요소들 중에 n 번째 요소 선택
            //저기 n자리에 꼭 숫자가 아니라 even 이나 odd 라고 적어도 짝수번째 홀수번째 선택할 수 있는 기능ㅇ이 있다.
            $("li:nth-child(3)").css("backgroundColor", "yellow");
            $("#view").text('$("li:nth-child(3)").css("backgroundColor", "yellow");');
        }
        
        function a7() {
            $("li:first-child").css("backgroundColor", "gray");
            $("#view").text('$("li:first-child").css("backgroundColor", "gray");');
        }

        function a8() {
            $("li:last-child").css("backgroundColor", "lime");
            $("#view").text('$("li:last-child").css("backgroundColor", "lime");');
        }

    </script>

</head>
<body>
    <h1>selector 표현식</h1>
    <div>
        <ul>
            <li><span>tag로 선택하기</span></li>
            <li id="t1">id로 선택하기</li>
            <li class="t2">class로 선택하기</li>
            <li><span>parent child로 선택하기</span></li>
            <li><b><span>parent &gt; child </span></b>로 선택하기 </li>
            <li>:nth-child() 로 선택하기</li>
            <li>:first-child로 선택하기</li>
            <li>:last-child로 선택하기</li>
        </ul>
    </div>
    <div>
        <button onclick="a1();">태그 선택 (span)</button>
        <button onclick="a2();">id로 선택(t1)</button>
        <button onclick="a3();">class로 선택 (t2)</button>
        <button onclick="a4();">p c 선택</button>
        <button onclick="a5();">p &gt; 선택</button>
        <button onclick="a6();">:nth-child() 선택</button>
        <button onclick="a7();">:first-child 선택</button>
        <button onclick="a8();">:last-child 선택</button>
    </div>
    <h2>코드 내용</h2>
    <div id="view"></div>
    
</body>
</html>