[JS] 이벤트 연결 (증가/감소)

2022. 2. 5. 11:22Javascript/이벤트

버튼 클릭시 숫자 증가 감소함을 보여줌

 

<!DOCTYPE html>
<html lang="en">
<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>증가 감소</title>
<body>
    <button class="plus">+ 버튼</button>
    <button class="minus">- 버튼</button>
    <h1 class="total">총 수량 : 0</h1>
</body>
</head>

<script>
document.addEventListener('DOMContentLoaded', () => {
    let counter = 0;
    const plus = document.querySelector('.plus');
    const minus = document.querySelector('.minus');
    const total = document.querySelector('.total');

    plus.addEventListener('click', () => {
        // for 문에서만 ++ 다른데에서는 += 1 이렇게 써야함 !!!!!!!
        counter += 1;
        total.textContent = `총 수량 : ${counter}`
    });

    minus.addEventListener('click', () => { 
        if (counter -1 < 0) {
        	return; // return 함수종료 !!!!
        }
        counter -= 1;
        total.textContent = `총 수량 : ${counter}`
    });
})
</script>
</html>

 

 

 

'Javascript > 이벤트' 카테고리의 다른 글

[JS] 이벤트 연결 해제  (0) 2022.02.04
[JS] reset 버튼  (0) 2022.01.20
[JS] 체크일때만 링크 활성화  (0) 2021.11.17
[JS] 우클릭방지  (0) 2021.11.17