Let's Go javascript (#2)

박호연·2021년 11월 4일
0

미니 프로젝트 (끝말잇기 놀이)const number = prompt('몇 명이 참가하나요?');

alert(number);

console.log,

alert - (x,y)같은형식은 지원하지 않는다 . 결과값에 하나만 적어야된다.

confirm - boolean 값만 취급한다. True or false 값을 나눌 때 사용하면 적합하다.

prompt 함수로 받은 모든 값은 모두 문자열로 취급된다. 그래서 숫자로 취급하려면 타입을 변경시켜야 한다. Number(n)과 같은 방식으로

const onClickButton = () => {
console.log('버튼 클릭');
};

Const 안에 console.log 를 넣을때 사용하는 식 = () =>

태그.addEventListener(‘이벤트함수’ , 리스너함수);

‘Click’, onClickButton 함수를 넣어 실행하는데 이때 중요한 점은 onClickButton()를
해서는 안된다는 것이다. 

()를 붙이는 순간 함수가 실행되기때문에

이때 onClickButton 같은 함수를 콜백함수라고한다. 콜백 함수는 특정 작업이 실행되고
난 뒤에 추가로 실행되는 함수를 의미한다.
이 같은 경우는 버튼을 클릭한 후에 onClickButton이 추가적으로 실행되므로 콜백함수라고 볼수있다.

완성된 끝말잇기 놀이

const number = Number(prompt('몇 명이 참가하나요?'));
const $button = document.querySelector('button');
const $input = document.querySelector('input');
const $word = document.querySelector('#word');
const $order = document.querySelector('#order');
let word; //제시어
let newWord; // 현재 단어

const onClickButton = () => {
// word 에 아무런 값을 넣지 않았으니 undefined 이다ㅏ if 문안에 들어가면 false로 취급되기 때문에
// !word 로 true로 취급되게끔 만들었다.
if(!word) { // 제시어가 비어 있는가?
word = newWord; // 입력한 단어가 제시어가 된다.
$word.textContent = word; // 화면에 제시어 표시

   const order = Number($order.textContent);
   if(order + 1 > number) {
       $order.textContent = 1;
   } else {
       $order.textContent = order + 1;
   }
}
else {
    // 비어 있지 않다.
    if(word[word.length - 1] === newWord[0]) { // 입력한 단어가 올바른가?
    // 올바르다.
    word = newWord; // 현재 단어를 제시어에 저장한다.
    $word.textContent = word; // 화면에 제시어 표시
    const order = Number($order.textContent);
    if (order + 1 > number) {
        $order.textContent = 1;
    }
    else {
        $order.textContent = order + 1;
    }

    } else {
        alert('올바르지 않은 단어입니다!')  // 올바르지 않다.
    }
}

};
const onInput = (event) => {
newWord = event.target.value; // 입력한 단어를 현재 단어로
};

button.addEventListener(click,onClickButton);button.addEventListener('click',onClickButton);input.addEventListener('input',onInput);

태그들의 내부 값을 가져올 때 어떤 속성을 사용해야 할까?

입력 태그 ( input, select, textarea)의 내부 값을 가져올때 .value 를 사용한다.

기타 (span, button, div) 등은 textContent 를 사용한다.

profile
주니어 개발자 박호연입니다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN