🗃️javascript/이론정리

javascript 이론(3)

하얀성 2022. 12. 26. 10:58
<!DOCTYPE html>
<html lang="ko">

<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>
</head>

<body>
  <div><span id="order">1</span>번째 참가자</div>
  <div>제시어: <span id="word"></span></div>
  <input type="text">
  <button>입력</button>
  <script>
    const number = Number(prompt('몇 명이 참가하나요?'), 10);
    const $button = document.querySelector('button');
    const $input = document.querySelector('input');// input태그 불러온 상태
    const $word = document.querySelector('#word'); // 화면도 같이 변경. 즉 제시어: 옆 빈칸으로 input값을 이동시켜준것.
    const $order = document.querySelector('#order'); // 화면도 같이 변경. 즉 제시어: 옆 빈칸으로 input값을 이동시켜준것.
   
    let word; // 제시어
    let newWord;  // 새로 입력한 단어

    const onClickButton = () => {
      if (!word || word[word.length - 1] === newWord[0]) {
        word = newWord;
        $word.textContent = word; // span 같은 대부분 값들은 textContent로 변경
       
        const order = Number($order.textContent);
        if (order + 1 > number) { // 다른 사람에게 순서 넘김
          $order.textContent = 1;
        } else {
          $order.textContent = order + 1;
        }
       
      } else {
          alert('올바르지 않은 단어입니다!')
      }
      $input.value = ''; // input같은 입력값들은 value로 변경
      $input.focus();
    };
    const onInput = (event) => {
      newWord = event.target.value; // 이벤트가 발생한 태크 즉, input 태그의 값을 가리켜서 newWord에 대입
    };

    $button.addEventListener('click', onClickButton);
    $input.addEventListener('input', onInput);
  </script>
</body>

</html>

 


 

<선언>
addEventListener('이벤트 이름', 리스너함수)
<선언코드 사용>
const 리스너 함수 = (event) => {console.log('문자열', event.target.value); }
리스너 함수의 매개변수로 event 객체를 제공해서 event.target.vaule처럼 이벤트와 관련된 정보 획득.
여기서 event.target는 이벤트가 발생한 대상 태그를 가리킴.

value 값 사용 : input , select, textarea 
textContent 값 사용 : button, div, span
입력창 포커스 input.focus();


<따라 그려본 순서도>

뒤에가서 알고리즘 중복내용을 수정해서 더 읽기 편한 코드로 수정했음.