[Javascript] 함수 이용해서 데이터 입력 및 삭제하기

소영·2022년 7월 9일
<body>
	<input type="text">
    <button class="input">click</button>
    <button class="del">delete</button>
    
    <div class="log"></div>
    
    <script>
    	const inputArray = ['hello', 'arry'];
        const input = document.querySelector('input');
        const buttonInput = document.querySelector('.input');
        const buttonDel = document.querySelector('.del');
        
        const log = document.querySelector('.log');
        
        
        function dataPrint(){
        	inputArray.forEach(function(data){
            	const div = document.createElement('div');
                div.innerHTML = data;	// 배열 데이터를 쓴 다음
                log.appendChild(div);	// DOM에 추가
            })
        }
        
        dataPrint();
        
        buttonInput.addEventListener('click', function(){
        	inputArray.push(input.value);
            log.innerHTML = "";
            dataPrint();
        })
        
        buttonDel.addEventListener('click', function(){
        	if(inputArray.includes(input.value)){
            	let num = inputArray.indexOf(input.value);
                delete inputArray[num];
           	}
            log.innerHTML = "";
            dataPrint();
       	})
        
        input.addEventListener('keyup', function(event){
        	// keyup : 키보드가 떼졌을 때
        	console.log(event.target.value);
        })
    </script>
</body>


실행 시 초기 화면


javascript, html 데이터 추가


arry 데이터 삭제

0개의 댓글