javascript

javascript_(이벤트위임_응용)_22.05.09(day11)

양빵빵 2022. 5. 9. 16:53

<!DOCTYPE html>
<html lang="ko">
<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">
    <title>Document</title>

    <style>
        #fruits {
            display: flex;
            flex-wrap: wrap;
            list-style: none;
            padding: 20px;
            border: 2px solid red;
        }
        #fruits li {
            width: 100px;
            cursor: pointer;
            background: orange;
            margin-right: 10px;
        }
        .active {
            color: red;
            text-decoration: underline;
        }
        label {
            display: block;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    
    <ul id="fruits">
        <li id="apple" class="active">Apple</li>
        <li id="banana">Banana</li>
        <li id="grape">Grape</li>
    </ul>

    <div>선택된 과일: <em class="msg">Apple</em></div>

    <label>
        # 새로운 과일 추가하기: 
        <input type="text" class="text-box">
        <button id="add">추가</button>
    </label>

 

// label 태그를 form으로 감싸면 엔터키를 눌러도 추가가 된다. form 태그에서 제공하는 기본 기능.



    <script>

        const $fruits = document.querySelector('#fruits');

        //이벤트 핸들러
        function activate(e) {
            
            if (!e.target.matches('#fruits > li')) {
                return;
            }

            for (let $li of [...$fruits.children]) {
                if ($li.classList.contains('active')) {
                    $li.classList.remove('active');
                    break;
                }
            }

            e.target.classList.add('active');

                        
            const $em = document.querySelector('.msg');
            $em.textContent = e.target.textContent;
        };

        
        $fruits.onclick = activate;

        //1. 추가버튼에 클릭이벤트 부여
        const $addBtn = document.getElementById('add');
        
        const makeNewLi = e => {  
            // console.log('추가버튼 클릭!');
            //2-1. li태그를 생성하여 인풋에 기록한 텍스트를 
            //     li태그의 텍스트로 삽입
            const $newLi = document.createElement('li');
            const $input = document.querySelector('.text-box');
            $newLi.textContent = $input.value; // <li>xxx</li>

            //2-2. li태그에 해당 텍스트를 아이디로 부여
            $newLi.setAttribute('id', $newLi.textContent.toLowerCase())
            
            //3. ul에 생성한 li를 추가
            $fruits.appendChild($newLi);

            //4. 인풋의 텍스트 초기화
            $input.value = '';
        };
        
        $addBtn.onclick = makeNewLi;
        

    </script>

</body>
</html>