본문으로 바로가기

cereateElement 사용하기

category JAVA개발자&안드로이드앱 개발 양성과정 2019. 11. 11. 22:29

이해 못 했던 부분.

1. forEach(); 메소드를 제데로 이해 못함. 

  The forEach() method calls a function once for each element in an array, in order.

2. addEventListener() 메소드를 제대로 이해 못 함.

  The addEventListener() method attaches an event handler to the specified element.

  addEventListener는 요소 하나에 각각 하나씩 붙는 메서드.

  document.querySelectorAll("li")은 배열인데 여기에 바로 메서드를 붙여줘서 type에러가 났음.

  꼭 for 또는 forEach를 사용해서 요소 하나씩을 선택한 후 addeventlistener를 붙여줘야함.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Step12_createElement2</title>
    <style>
        #toDoList li:hover{
            background-color: yellow;
            cursor: pointer;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <h1>creatElement()테스트</h1>
    <input type="text" id="inputMsg" placeholder="할일 입력"/>
    <button id="addBtn">추가</button>
    <ul id="toDoList">
        <li>시험보기</li>
        <li>침대에서 요양하기</li>
    </ul>
    <script>
        //input 요소의 참조값을 얻어와서 변수에 담아 놓는다.
        var inputElem=document.querySelector("#inputMsg");
        
        function add(){
            var b=inputElem.value;
            //2. li요소를 만든다
            var a=document.createElement("li");
            //3. li요소의 innerText로 입력한 문자열을 넣어준다.
            a.innerText=b;
            //4. ul의 자식요소로 li를 추가한다
            document.querySelector("#toDoList").append(a);
            //5. 입력한 내용 삭제하기
            inputElem.value="";
            //6. input 요소에 입력하기 편하도록 포커스 추가
            inputElem.focus();
            //7. 새로만들어진 li 요소에도 click 이벤트를 추가 하기
            a.addEventListener("click", function(){
                var isDelete=confirm("삭제하시겠습니까?");
                if(isDelete==true){
                    //클릭이벤트가 일어난 바로 그 요소 삭제
                    this.remove();
                }
            });
        };



        document.querySelector("#addBtn").addEventListener("click", function(){
            add();
        });
        
        //enter key를 클릭했을때 li 글씨가 추가 되도록하기
        document.querySelector("#inputMsg").addEventListener("keyup",function(e){

            console.log(e.keyCode);
            
            if(e.keyCode==13){
                add();
                // var b=document.querySelector("#inputMsg").value;
                // var a=document.createElement("li");
                // a.innerText=b;
                // document.querySelector("#toDoList").append(a);
            }else{
                return;
            }
        });


        //log를 클릭하면 삭제할까요?라고 묻는 팝업띄우기
        // 첫번째 li 요소만 선택됨.
        // document.querySelector("#toDoList li").addEventListener("click",function(){
        //     var isDelete=confirm("삭제하시겠습니까?");
        //     if(isDelete==true){
        //         this.remove();
        //     }
        // });
        //반복문(forEach)을 통해 모든 li를 선택 할 수 있도록함.
        document.querySelectorAll("#toDoList li").forEach(function(item){
            item.addEventListener("click", function(){
                var isDelete=confirm("삭제하시겠습니까?");
                if(isDelete==true){
                    //클릭이벤트가 일어난 바로 그 요소 삭제
                    this.remove();
                }
            });
        });
        

        // //인자로 전달되는 선택자를 이용해서
        // function $(sel){
        //     //해당 문서 객체의 참조값을 리턴해주는 함수
        //     var ref=document.querySelector(sel);
        //     return ref;
        //};
    </script>
</body>
</html>