HTML
<!DOCTYPE html>
<html lang="en">
<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>
<script type="text/javascript" defer src="./index.js"></script>
</head>
<body>
<div><span id="order">1</span>번째 참가자</div>
<div>제시어: <span id="word"></span></div>
<input type="text">
<button>입력</button>
</body>
</html>
Index.js
const number = parseInt(prompt("몇 명이 참가하나요?"), 10);
//prompt에서 취소를 누르는 경우 null이 되고, 그 값이 Number()함수에 들어가면
//NaN이 된다. NaN은 if문에 널어가면 항상 false취급되므로 if문 실행X
if (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 = () => {
// 제시어가 비어 있는가? 또는 올바른가?
if (newWord.length === 3 && (!word || word[word.length - 1] === newWord[0])) {
//새로운 단어의 길이가 3이고, (제시어가 없거나, 입력한 단어가 제시어의 끝글자와 일치)하는 경우
word = newWord; // 입력한 단어가 제시어가 된다.
$word.textContent = word;
$input.value = "";
// 참가 순서를 1 증가시킨다.
let order = parseInt($order.textContent, 10);
if (order + 1 > number) {
$order.textContent = 1; // 자동형변환
} else {
$order.textContent = order + 1;
}
} else if (word[word.length - 1] !== newWord[0]) {
// 끝말이 아닌 경우
alert("올바르지 않은 단어입니다!");
} else if (newWord.length !== 3) {
// 단어의 길이가 3이 아닌 경우
alert("길이가 맞지 않습니다.");
} else {
alert("틀렸습니다.");
}
$input.value = "";
$input.focus();
};
const onInput = (event) => {
newWord = event.target.value; // 마지막 끝값이 새로운 단어가 된다.
};
$button.addEventListener("click", onClickButton);
$input.addEventListener("input", onInput);
}
'렛츠기릿 자바스크립트' 카테고리의 다른 글
렛츠기릿 자바스크립트 7 (계산기) -self(연달아 계산) (0) | 2023.01.09 |
---|---|
렛츠기릿 자바스크립트 7 (계산기) + 고차함수 + if중첩문 제거 (0) | 2023.01.08 |
렛츠기릿 자바스크립트 6 (끝말잇기) (0) | 2023.01.08 |
렛츠기릿 자바스크립트 5 (0) | 2023.01.08 |
렛츠기릿 자바스크립트4 (함수, 객체) (0) | 2023.01.08 |