많은 예제를 접해보며
간단하게 배웠던 코드들이 어떻게 사용되는지
확인해 볼 수 있다. 신기하고 또 재미있다
.......
나도 저렇게 사용할 수 있겠지?
input으로 들어오는 값과 변환할 상수들 (select option)들 곱해서 span자리에 변환값을 출력해주는 프로그램이다
<script>
document.addEventListener('DOMContentLoaded',()=>{
let current = ''
let changeNum = 10
const select = document.querySelector('select')
const input = document.querySelector('input')
const span = document.querySelector('span')
const calculate = ()=>{
span.textContent =(current * changeNum).toFixed(2)
// current와 changeNum을 구해 곱한 뒤, // 소수2째자리까지 출력
// 결과값을 span에 textContent추가한다
}
select.addEventListener('change',(e)=>{
const options = e.currentTarget.options
const index = e.currentTarget.options.selectedIndex
changeNum = Number(options[index].value) // option[index].value = 10, 0.1, 0.39....
calculate() // 함수실행 changeNum 값 들어감
})
input.addEventListener('keyup',(e)=> {
current =Number(e.currentTarget.value) // input에 입력된 currentTarget값 Num으로 담아
calculate() // 함수실행 current 값 들어감
})
})
</script>
<body>
<input type="text"> cm =
<span></span>
<select>
<option value="10">mm</option>
<option value="0.01">m</option>
<option value="0.393701">inch</option>
</select>
</body>
'개발공부_Blog > JavaScript' 카테고리의 다른 글
javascript - 화살표함수 (0) | 2021.12.23 |
---|---|
javascript - radio버튼 (0) | 2021.12.22 |
javascript - 함수의 다양한 형태 (0) | 2021.12.22 |
javascript - for문의 종류 (for in / for of / for Each ) (0) | 2021.12.22 |
javascript - 반복문으로 최대최소값 구하기 (0) | 2021.12.22 |
댓글