본문 바로가기
개발공부_Blog/JavaScript

javascript - cm를 여러 단위로 변환

by 소팡팡 2021. 12. 22.

 

 

많은 예제를 접해보며
간단하게 배웠던 코드들이 어떻게 사용되는지 
확인해 볼 수 있다. 신기하고 또 재미있다
.......
나도 저렇게 사용할 수 있겠지?

 

 

 

 

 

 

 

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>

 

댓글