[HTML][JS] Closer 활용 (상태를 변경할 수 있는 버튼)
클로저가 가장 유용하게 사용되는 상황은 현재상태를 기억하고 변경된 최신상태를 유지하는 것이다.
toggle버튼을 누를때마다 빨간박스의 상태가 변하는 코드를 작성해 보았다.
수도코드 작성
<!DOCTYPE html>
<html>
<body>
<button class="toggle">toggle</button>
<div class="box" style="width: 100px; height: 100px; background: red;"></div>
<script>
클래스가 box인 엘리먼트를 변수box에 할당
클래스가 toggle인 엘리먼트를 변수 toggleBtn에 할당
버튼의 상태가 어휘적환경에 의해 메모리에 저장될 수 있게
변수명이 toggle인 클로저 함수를 만들고
버튼의 상태를 할당한 변수isShow 만들기
콜백함수에 isShow의 상태에 따라 CSS의 display가 변하는 조건 만들기
toggleBtn 클릭시 toggle함수 실행
</script>
</body>
</html>
코드 작성
<!DOCTYPE html>
<html>
<body>
<button class="toggle">toggle</button>
<div class="box" style="width: 100px; height: 100px; background: red;"></div>
<script>
var box = document.querySelector('.box');
var toggleBtn = document.querySelector('.toggle');
var toggle = (function () {
var isShow = false;
return function () {
if(isShow){
console.log('on')
box.style.display = 'block'
isShow = !isShow
} else if(!isShow) {
console.log('off')
box.style.display = 'none'
isShow = !isShow
}
};
})();
toggleBtn.onclick = toggle;
</script>
</body>
</html>
Author And Source
이 문제에 관하여([HTML][JS] Closer 활용 (상태를 변경할 수 있는 버튼)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@tyoon225/HTMLJS-Closer-활용저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)