본문 바로가기
ICIA 수업일지

2021.07.28 수업일지

by 주성씨 2021. 7. 31.

- Java Script Review

- DOM(Document Object Model)

 

18_3_heap

<body>
    <script>
        let arr = []; // {}
        main(); // var 변수 함수 정의부가 호이스칭 되어 호출 가능
        function main() {
            let list1 = [1, 2, 3];
            let list2 = [1, 2, 3];
            console.log(list1 == list2); // 배열의 참조값 비교 : false
            let a = "list";
            let b = "list";
            console.log("list" == "list"); // 내용 비교 : true
            console.log(a == b);

            let arr = createArray();
            arr.fill(9);
            showArr(arr);
            const fct = createFct(); // 변경하고 싶지 않은 변수는 const로 
            fct(3);
        }

        function createArray() {
            let arr = [1, 2, 3, 4]; // 객체, 배열, 함수는 참조타입이므로 힙에 저장됨
            return arr;
        }

        function showArr(arr) {
            for (let val of arr) {
                console.log(val);
            }
            console.dir(arr);
        }

        function createFct() {
            // return function (n) {
            //     for (let i = 0; i < n; i++) {
            //         console.log(i + "함수 호출");
            //     }
            // }

            // 람다식
            return (n) => {
                for (let i = 0; i < n; i++) console.log(i + "함수 호출")
            }
        }
    </script>
</body>

 

17_elemChange Review

<body>
    <p id="p1"></p>
    <button id="btn">innerHTML</button><br>
    <img id="image" src="img\img01.jpg" alt="버섯돌이"><br>
    <button id="imgchanger">이미지 변경</button>
    <script>
        let elem = document.getElementById("p1");
        let btn = document.getElementById("btn");
        btn.addEventListener('click', () => elem.innerHTML = "새로운 <b>텍스트</b> 등장");

        let elem2 = document.getElementById('image');
        let btn2 = document.getElementById("imgchanger");
        btn2.addEventListener('click', function () {
            console.dir(elem2);
            elem2.src = 'img/img04.jpg'; // 객체 property 속성
            // elem2.setAttribute("src","img/img04.jpg"); // html 태그의 속성 변경
        })
    </script>
</body>

 

19_elemChanger2 ; 클릭시 배열에 저장해 놓은 색으로 글자색이 변경되는 코드

<body>
    <h1 id="p1">글자 색상이 변경 된다.</h1>
    <button id="btn">색상 변경</button>
    <script>
        let elem = document.getElementById("p1");
        let btn = document.getElementById("btn");

        let fontColor = ["#e0ffff", "#b0e0e6", "#afeeee", "#add8e6", "#87ceeb", "#87cefa", "#00bfFf"];
        let i = 0;

        btn.addEventListener('click', function () {
            if (i == fontColor.length) {
                i = 0;
            }
            console.log(i);
            elem.setAttribute("style", "color:" + fontColor[i++]);
        });
    </script>
</body>

 

20_elemGetAttr

<body>
    <input type="text" value="동해물과 백두산이">    
    <input type="text" value="마르고 닳도록">
</body>

 

1. 속성을 이용한 출력

    <script>
        let tags = document.getElementsByTagName("input"); // 반환값 collection 배열
        console.log(tags);
        // 속성을 이용한 출력
        for(let i=0;i<tags.length;i++){
            // 1. getAttribute를 이용해서 출력
            // console.log(tags[i].getAttribute('type'));
            // console.log(tags[i].getAttribute('value'));

            // 2. 객체의 property를 이용해서 출력
            console.log(tags[i].type);
            console.log(tags[i].value);
        }
    </script>

 

2. 속성 변경

        // 속성 변경
        // 1. 객체의 property를 이용한 값 변경
        tags[0].type = 'button';
        tags[0].value = 'click';
        // 2. setAttrubute를 더 많이 사용
        tags[1].setAttribute('type','button');
        tags[1].setAttribute('value','클릭');

 

3. 속성 추가

        // 속성 추가
        // tags[0].setAttribute('onclick',"alert('hi');");
        tags[0].onclick=()=>alert('hi');

 

21_elemAttrProp - checked, readonly, disabled 속성은 property로 설정해야 한다.

<body>
    <input id="chk" type="checkbox"><br>
    <button id="ckbtn1">체크상태값 확인</button>
    <button id="ckbtn2">체크상태값 설정</button><br>
    <hr>

    <input id="txt" type="text"><br><br>
    <button id="txtbtn1">텍스트상태 확인</button>
    <button id="txtbtn2">텍스트상태 설정</button>
</body>

 

1. 텍스트

    <script>
        // TEXT
        let txt = document.getElementById('txt');
        let txtbtn1 = document.getElementById('txtbtn1');
        let txtbtn2 = document.getElementById('txtbtn2');

        //text상자 상태값
        txtbtn1.addEventListener('click', function () {
            //태그에 disabled, readonly 속성이 없으면 null or ""반환 
            // console.log("attr disabled:", txt.getAttribute('disabled'));
            // console.log("attr readonly:", txt.getAttribute('readonly'));
            //설정시 true, 아님 false
            console.log("prop disabled:", txt.disabled);
            console.log("prop readonly:", txt.readOnly);
        });
        txtbtn2.addEventListener('click', function () {
            //txt.setAttribute('disabled','disabled');//설정은 되지만 해제를 못함  
            //txt.setAttribute('readonly','readonly');//설정은 되지만 해제를 못함  
            txt.disabled = true; //false로 해제도 가능  
            txt.readOnly = true; //false로 해제도 가능  
        });
    </script>

 

2. 체크박스

    <script>
        //CHECKBOX
        let chk = document.getElementById('chk');
        let ckbtn1 = document.getElementById('ckbtn1');
        let ckbtn2 = document.getElementById('ckbtn2');

        // 체크박스 상태 확인버튼
        ckbtn1.addEventListener('click', function () {
            //태그에 checked 속성이 없으면 null반환 
            console.log(chk.getAttribute('checked'));
            //설정시 true, 아님 false
            console.log(chk.checked); //체크상태값 실시간 반영
        });
        ckbtn2.addEventListener('click', function () {
            // checked 속성은 setAttr getAttr를 사용해서는 안된다.
            // 웹 상 체크박스를 해체하더라도 요소에는 그대로이기 때문이다.
            // chk.setAttribute('checked','checked');
            chk.checked = true; // property로 값을 넣어야 한다.
        });
    </script>

 

22_elemAgetAttr!

<body>
    <a href="#" data-xxx="header">link click</a>
    <a href="#" data-xxx="main">link click</a>
    <a href="#" data-xxx="footer">link click</a>
    <button>change</button>

    <script>
        let tags = document.getElementsByTagName("a");
        let btn = document.querySelector("button");

        btn.addEventListener("click", function () {
            for (let i = 0; i < tags.length; i++) {
                //let attr=tags[i].data-role;  //에러
                let attr = tags[i].getAttribute("data-xxx");
                if (attr == "header") {
                    tags[i].innerHTML = "<h1>HEADER</h1>";
                }
                if (attr == "main") {
                    tags[i].innerHTML = "<h1>MAIN</h1>";
                }
                if (attr == "footer") {
                    tags[i].innerHTML = "<h1>FOOTER</h1>";
                }
            }
        });
    </script>

</body>

 

23_keyUpEvent - 확인요망

 

- Element 추가 및 삭제

method desciption
document.createElement(); 앨리먼트 만들기
document.removeChild(); 자식 요소 지우기
document.appendChild(); 자식 요소 추가
document.replaceChild(); 자식 요소 교체

 

24_elemAddDel

<body>
    <input id="val" type="text" />
    <button type="button" onclick="addList()">추가</button>
    <br>
    <!-- <ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul> -->

    <!-- li 사이에 엔터(#text)가 들어가 있으니 요소 삭제시 감안해야한다. -->
    <ul id="myList">
        <li>Coffee</li>
        <li>Tea</li>
        <li>Milk</li>
    </ul>

    <button id="btn1">엘리먼트 추가</button>
    <button id="btn2">자식요소 지우기</button>
    <button id="btn3">자식요소 교체</button>
    <script>
        //요소 변경하기: li태그 줄바꿈 삭제후 테스트할 것.
        document.getElementById('btn3').addEventListener('click', function () {
            let txtNode = document.createTextNode('Water');
            let item = document.getElementById('myList').childNodes[0]; //<li>coffee</li>
            item.replaceChild(txtNode, item.childNodes[0]);
        });


        // 앨리먼트 추가
        document.getElementById('btn1').addEventListener('click', function () {
            // let tNode = document.createTextNode('New click');
            // let btn = document.createElement('button');
            // btn.appendChild(tNode);
            // // 웹 페이지에 추가
            // document.body.appendChild(btn);

            // input 태그로 버튼 만들어보기
            let ipBtn = document.createElement('input');
            ipBtn.setAttribute('value', 'click me');
            ipBtn.setAttribute('type', 'button');
            ipBtn.setAttribute('class', 'bClass');
            document.body.appendChild(ipBtn);
        });

        //리스트 요소 지우기
        document.getElementById('btn2').addEventListener('click', function () {
            let myList = document.getElementById('myList'); //ul
            //첫번째 리스트 삭제
            //console.dir(myList);
            //if (myList.firstChild.nodeName == '#text') {
            // if (myList.childNodes[0].nodeName == '#text') {
            //     myList.removeChild(myList.childNodes[0]); //엔터 삭제
            //     myList.removeChild(myList.childNodes[0]); //li 삭제
            // } else {
            //     myList.removeChild(myList.childNodes[0]); //li 삭제
            // }

            // 마지막 리스트 부터 삭제
            myList.removeChild(myList.childNodes[myList.childNodes.length - 1]);
        });


        // // 앨리먼트 삭제
        // document.getElementById('btn2').addEventListener('click', function () {
        //     let btns = document.querySelectorAll('.bClass');
        //     // 첫째 버튼 삭제
        //     document.body.removeChild(btns[0]);
        // });

        function addList() {
            let txt = document.getElementById('val').value;
            let myList = document.getElementById('myList');
            // 내부적으로 <li></li> 생성
            let lielem = document.createElement('li');
            // Juice Node로 생성
            let txtNode = document.createTextNode(txt);
            // 내부적으로 <li>txt</li>를 생성
            lielem.appendChild(txtNode);
            myList.appendChild(lielem);

            // let myList = document.getElementById('myList');
            // let lielem = document.createElement('li');
            // let txtNode = document.createTextNode("Juice");
            // lielem.appendChild(txtNode);
            // myList.appendChild(lielem);
            // //myList.prepend(lielem);

        }
    </script>

</body>

 

- BOM(Browser Object Model) ;  웹 부라우저를 하나의 객체로 인식하여 브라우저 내의 기능을 핸들링 한다.

25_window

<head>
    <meta charset="UTF-8">
    <title>window</title>
    <script>
        // function fct() {
        //     alert("id='info' 검색")
        //     console.log(document.getElementById("info"));
        // }

        window.onload = () => {
            alert("id='info' 검색")
            console.log(document.getElementById("info"));
        }
    </script>
</head>

<!-- <body onload="fct()"> -->

<body>
    <!-- onload ; 브라우저가 모든 페이지를 로딩 한 후(가장 처음 일어나는) -->
    <p id="info">값 출력</p>
    <button>창열기</button>
    <button>창닫기</button>
    <button>창이동</button>
    <button>창크기 변경</button>

    <script>
        // propoerty를 이용한 브라우저 사이즈 측정
        let w = window.innerWidth;
        let h = window.innerHeight;
        let info = document.getElementById('info');
        info.innerHTML = "현재 부라우저 크기는 width : " + w + ", height : " + h;

        let btns = document.getElementsByTagName('button');
        let mywindow;
        // 창 열기 *****
        btns[0].addEventListener('click', function () {
            //파라미터: "url", "title"(지정된 타이틀(이름)을 가진 윈도우가 없으면 새 창이 열림), "option"
            /*option => scrollbars=yes||no, resizable=yes||no, top=100, left=100 등등*/
            //크롬에선 옵션이 안먹을 수 있음.
            mywindow = window.open("26_childWindow.html", "Popupwin",
            "width=200, height=400, left=200, top=200");
        })

        // 창 닫기 *****
        btns[1].addEventListener('click', () => mywindow.close());

        // 창 이동
        btns[2].addEventListener('click', () => {
            mywindow.moveTo(300, 100); //moveBy:계속 이동
            mywindow.focus(); //창 활성화
        });

        // 창 크기 변경
        btns[3].addEventListener('click', () => {
            mywindow.resizeTo(250, 250); //resizeBy:계속 크기변경
            mywindow.focus(); //창 활성화
        });
        function fct(){
            console.log("did you call me?")
            return true;
        }
    </script>

</body>

 

26_childWindow

<body>
    <h3>자식 페이지</h3>
    <h2>opener 객체 : 부모 페이지를 의미</h2>
    <script>
        // 하나씩 확인해보기 ***

        // console.log(window.opener); //부모창
        //부모창의 id가 info인 개체의 값
        // console.log(opener.document.getElementById('info').innerHTML);
        // console.log(window.opener.fct()); //부모창의 fct() 호출
        // window.self.close();  //팝업창 닫기
        // opener.close(); //부모창 닫기
        //opener.location.href="http://www.naver.com"; //부모창 주소 이동
        // document.location.reload(); //현재창 새로고침
        // opener.location.reload(); // 부모창 새로고침
    </script>
</body>

ㄴ 자식창과 부모창의 연동을 확인해보도록 하자.

 

  • location - 현재 페이지의 url을 반환 한다. *****
  • history.back - 뒤로 이동 
  • history.forward - 앞으로 이동
<body>
    <p>Display the entire URL of the current page.</p>
    <p id="demo"></p>
    <button id="loc">네이버 페이지로 이동 </button>
    <input type="button" value="뒤로가기" onclick="goBack()">
    <input type="button" value="앞으로 가기" onclick="goForward()">
    <script>
        document.getElementById("demo").innerHTML = "Page location is: " + window.location.href;

        document.getElementById('loc').addEventListener("click", function () {
            location.href = "http://www.naver.com";
        });

        // 이전 페이지 이동
        function goBack() {
            // window.history.back() // ※주의. 서버가 아닌 로컬PC에서 가져옴
            history.back();
            // history.go(-1);
        }

        // 앞전 페이지 이동
        function goForward() {
            window.history.forward()
        }
    </script>
</body>

 

  • alert - 가장 자주 쓰는 경고창
  • confirm - 액션 실행 전 확인(취소 버튼이 존재)
  • prompt - 유저에게 입력을 받는 창

 

29_timing *****

<body>
    <button onclick="interval()">증가</button>
    <button onclick="stop()">정지</button>
    <button onclick="setTime()">3초후 경고창</button>
    <h1 id="msg">0</h1>
    <script>
        let myTime;
        let x = 0;
        let msg = document.getElementById("msg");

        //타이머 시작 함수
        function interval() {

            myTime = setInterval(function () {
                x++;
                msg.innerHTML = x;
            }, 1000);

        }

        function stop() {
            clearInterval(myTime);
            x = 0;
            msg.innerHTML = x;
        }

        function setTime() {
            //타이머 함수는 비동기 함수
            //interval(); //interval함수 실행중에도 setTimeout함수가 실행된다.
            setTimeout(function () {
                alert("3초가 지났네요");
                //location.href="http://www.naver.com";
            }, 3000);

        }
    </script>
</body>

 

30_timing2

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #count {
            color: red;
        }
    </style>
</head>

<body>
    <!-- location.href = "http://www.google.com"; -->
    <h1><span id="count">10</span> 초 후 페이지가 이동 됩니다.</h1>
    <script>
        let cnt = 10;
        let msg = document.getElementById("count");

        setInterval(function () {
            cnt--;
            msg.innerHTML = cnt;
        }, 1000);

        setTimeout(function () {
            alert("페이지가 이동 됩니다.");
            location.href = "http://www.google.com";
        }, 10000);
    </script>
</body>

 

31_timing3

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #obj {
            position: absolute;
            width: 30px;
            height: 30px;
            background-color: cadetblue;
            top: 50px;
            left: 0px;
        }
    </style>

</head>

<body>
    <button onclick="left()">◀</button>
    <button onclick="right()">▶</button>
    <button onclick="stop()">■</button>
    <div id="obj"></div>

    <script>
        let obj=document.getElementById("obj")
        let btn = document.getElementsByTagName('button');
        let x=0;
        let move;

        function right() {
            let i = 0;
            move = setInterval(function () {
                if (i <= 100) {
                    i++;
                    x = x + 1;
                    btn[0].disabled = true;
                    btn[1].disabled = true;
                } else {
                    stop();
                    i = 0;
                }
                obj.style.left = x+"px";

            }, 100);
        }

        function left() {
            let i = 0;

            if (x <= 0) {
                alert("이동 할 수 없습니다.");
            } else {
                move = setInterval(function () {
                    if (i <= 100) {
                        i++;
                        x = x - 1;
                        btn[0].disabled = true;
                        btn[1].disabled = true;
                    } else {
                        stop();
                        i = 0;
                    };
                    obj.style.left = x+"px";
                }, 100);
            }
        }

        function stop() {
            clearInterval(move);
            btn[0].disabled = false;
            btn[1].disabled = false;
        }
    </script>
</body>

'ICIA 수업일지' 카테고리의 다른 글

2021.07.30 수업일지  (0) 2021.07.31
2021.07.29 수업일지  (0) 2021.07.31
2021.07.27 수업일지  (0) 2021.07.31
2021.07.26 수업일지  (0) 2021.07.31
2021.07.23 수업일지  (0) 2021.07.24