[자바스크립트] 틀렸을 때 오류 표시하기

휘루·2023년 6월 23일
0

자바스크립트

목록 보기
29/40

오류 표시하기

올바르지 않은 경우 alert 함수를 씁니다.
나중에 가면 alert을 안쓰고 화면에다가 글자 적는 경우도 있습니다.

alert('올바르지 않은 단어입니다.');

포커스 넣기

시작할 때 자동으로 입력하기 좋게 커서를 활성화 하는 방법입니다.

$input.focus();

를 넣어주면 됩니다. 세군데 넣을 건데요.

처음은 저곳에 넣고

두번째는 아래쪽에

마지막으로 포커스는 올바르지 않은 else 보다는 위에 넣습니다.

이렇게 넣어주면 끝.

제시어 비우기

제시어 비우기는

$input.value = '';

인데 기존 자리에서 아래쪽으로 옮겨 넣어도 구동이 됩니다.
$input인 만큼 focus와 가까이 놓았습니다.

완성한 끝말잇기 코드

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <span id="order">1</span>번쩨 참가자</div>
    <div>제시어: <span id="word"></span></div>
    <input type="text" placeholder="내용을 입력하세요.">
    <button>입력</button>
    <script>
        const number = parseInt(prompt('몇명이 참가하나요?'), 10);
        const $button = document.querySelector('button');
        const $input = document.querySelector('input');
        const $word = document.querySelector('#word');
        const $order = document.querySelector('#order');
        let word; // 제시어 변수 저장하는 곳 (당장 안써도 미리 만들어 놓습니다.)
        let newWord; // 새로 입력한 단어 저장하는 곳
        $input.focus(); // 입력창 포커스입니다. input창 커서를 자동으로 깜빡거리는 기능입니다. (인원 입력 후 아주 처음부터 포커스on 가능)

        const onClickButton = () => { // 버튼을 클릭했을 때 제시어가 없다(if(!word)) 없다는 앞에 !붙이면 됩니다.
            if (!word) { // 제시어가 비어 있는가?
                word = newWord; // 입력한 단어가 제시어가 됩니다. 데이터를 바꿨으니 화면도 바꿔줘야 합니다.
                $word.textContent = word; // $word를 textContent(텍스트 불러오기 명령어)해줍니다. 제시어를 연결해야 되니 word를 연결합니다.
                const order = Number($order.textContent); // 현재 순서는 order 1입니다. 일부러 1로 해놓고 #order 1을 span으로 감쌌습니다.
                
                // 문자열을 숫자로 돌릴려면 parseInt를 씁니다.
                // 앞으로 parseInt랑 Number 지겹게 보실겁니다. 여기서는 order = Number(); 입력합니다.
                // 그래서 parseInt($order.textContent); 인데 잠깐 const로 order를 잠깐 저장합니다.
                // 저장해야겠다고 생각하면 변수를 떠올려서 저장하면 됩니다.

                if (order + 1 > number) { // 현재순서 + 1이 Number보다 크면 혹은 order + 1이 Number와 ===일 경우, 일단은 order + 1 > Number로 하겠습니다.
                    $order.textContent = 1; // << 여기 있는 문자열 1은 굳이 꼭 안넣어줘도 됩니다. textContent에 어떤 값 넣으면 1이 자동으로 형변환 되서 문자열로 들어갑니다.
                } else {
                    $order.textContent = order + 1; // 해석하면 28번줄의 현재 순서를 가져와서 -> 34번줄에서 판단하고 -> 35번은 1번으로 돌리는 결과 -> 37번은 다음 순서로 넘기는 결과입니다. 순서도를 정확히 그릴 줄 알아야 코드에 그대로 나옵니다.
                };
                $input.value = ''; // 입력창 비우기입니다. 제시어 입력 후 다음단어를 비우기 위해 ''으로 공백 처리합니다.
                $input.focus(); // 입력창 포커스입니다. input창 커서를 자동으로 깜빡거리는 기능입니다.
            } else {
                // 비어있지 않다 (안 비어있는 경우 `입력 단어가 올바른지`, `틀렸다고 표시`를 코딩합니다.)
                if (word[word.length - 1] === newWord[0]) { // 첫 제시어의 마지막 단어 === newWord[0]첫번째 단어가 같은가?를 ===으로 비교.
                    word = newWord; // 입력한 단어가 제시어가 됩니다. 데이터를 바꿨으니 화면도 바꿔줘야 합니다.
                    $word.textContent = word;
                    const order = Number($order.textContent);
                    if (order + 1 > number) {
                        $order.textContent = 1;
                    } else {
                        $order.textContent = order + 1;
                    }
                    $input.value = '';
                    $input.focus();
                } else { // 올바르지 않은가?
                    alert("올바르지 않은 단어입니다");
                };
            };
        };

        const onInput = (event) => {
            newWord = event.target.value;
        };

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

퀴즈

다음 태그의 내부 값을 가져올 때 둘 중 어느 속성을 사용해야 할까요?

  • input (value / textContent)
  • button (value / textContent)
  • select (value / textContent)
  • div (value / textContent)
  • textarea (value / textContent)
  • span (value / textContent)

답안 : input.value / button.textContent / select.value / div.textContent / textarea.value / span.textContent
해석 : input, select, textarea만 value이고 나머지는 textContent로 보시면 됩니다.

profile
반가워요

0개의 댓글