range input
์ ํตํด 0~250 ์ฌ์ด์ ์ซ์๋ฅผ ์ฌ์ฉ์๊ฐ ์ ํํ๋๋กํ๊ณ , ์ ํํ ๋ฒ์๋ด์์ Math.random()
์ ํตํด ์ ์ ํ๋๋ฅผ ์ ํํ๊ณ , ์ฌ์ฉ์๊ฐ input
์ ์
๋ ฅํ ์ซ์์ ๊ฐ์ ์ซ์์ธ์ง๋ฅผ play! button
์ด ํด๋ฆญ๋์์ ๋ ํ์ธํ๋๋กํ๋ค. ํด๋ฆญ๋ง๋ค ์๋ก์ด ์ซ์๋ฅผ ์ ํํ๋ค.
input range
๋ฅผ ์ฌ์ฉ
์ฌ์ฉ์์ ๋ฒ์ ์ค์ ์ ์ค์๊ฐ์ผ๋ก ๋ฐ์
์ฌ์ฉ์์ ์ซ์๊ฐ ์ ํ๋์ง ์์๋ค๋ฉด play!button
์ด ๋์ํ์ง ์๋๋ก
<<h1>Random Number Game</h1>
<h2 class="js-notice">Generate a Number between 0 and</h2>
<input type="range" class="js-range" min="0" max="250" />
<p>
Guess the Number!
<input class="js-input" type="number" min="0" max="250" width="200" />
<button class="js-button">play!</button>
</p>
<span class="js-span"></span>
<h4 class="js-result"></h4>
html ํ์ผ์ ๋ค์๊ณผ ๊ฐ์ด ์์ฑํ์๋ค. "js-notice"
๋ ์ฌ์ฉ์์ input range
์ ๊ฐ์ ๋ฐ๋ผ ํด๋น ๊ฐ์ ๋ฐ์ํ๋๋ก ํ์๊ณ , "js-input"
์ ์ฌ์ฉ์์ ์
๋ ฅ์ ๋ฐ๊ณ , "js-span"
๊ณผ "js-result"
์์๋ ๊ฐ๊ฐ ์ฌ์ฉ์์ ์ปดํจํฐ์ ๊ฐ๊ณผ ์นํจ์ฌ๋ถ๋ฅผ ๋ฐ์ํ๋๋ก ํ์๋ค.
js ํ์ผ์์๋ ์๋์ ๋ด์ฉ๊ณผ ๊ฐ์ด html ํ๊ทธ๋ค์ ์ฌ์ ์ ์ ์ธํด ์ฃผ์๊ณ ,
const range = document.querySelector(".js-range");
const notice = document.querySelector(".js-notice");
const input = document.querySelector(".js-input");
const button = document.querySelector(".js-button");
const span = document.querySelector(".js-span");
const result = document.querySelector(".js-result");
init()
ํจ์ ๋ด๋ถ์๋ addEventListener()
๋ฅผ ํตํด range
์๋ input
event์ ๋ํด, button
์๋ click
event์ ๋ํด ๋ฐ์ํ๋๋ก ํ์๋ค.
input event์ ๋ํ ๋ฐ์์ผ๋ก ์๋๋๋ ํจ์ handleInput()
์ ์ฌ์ฉ์๊ฐ input range
๋ก ์ง์ ํ ๊ฐ์ notice
์ ๋ด์ฉ์ผ๋ก ํฌํจ์ํค๋๋ก ํ๋ ํจ์์ด๋ค.
function handleInput(event) {
const value = event.target.value;
notice.innerText = `Generate a Number between 0 and ${value}`;
}
play! button
์ ํด๋ฆญํ๋ฉด ๋ฐ์ํ๋ ํจ์ handleClick()
์ input.value
๋ฅผ value
๋ก์ ์ ์ฅํ๊ณ , ์กฐ๊ฑด๋ฌธ์ ํตํด value !== ""
์ธ ๊ฒฝ์ฐ์๋ง ์ ๋ต ๋น๊ต๋ฅผ ์งํํ๋๋ก ํ์ฌ, input
์ ์๋ฌด๊ฒ๋ ์
๋ ฅ์ด ๋์ง ์์ ๊ฒฝ์ฐ๋ฅผ ๋ฌด์ํ๋๋ก ํ์๋ค.
const answer = Math.floor(Math.random() * range.value);
span.innerText = `You chose : ${value}, the machine chose : ${answer}`;
if (parseInt(value) === answer) {
result.innerText = "YOU WIN!";
} else {
result.innerText = "YOU LOST!";
}
์ดํ ์์ ๊ฐ์ ๋ด์ฉ์ ์ฝ๋๋ฅผ ํตํด value
์ ๊ฐ๊ณผ answer
์ ๊ฐ์ ๋น๊ตํ์ฌ ํด๋นํ๋ ๋ด์ฉ์ผ๋ก innerText
๋ฅผ ์์ ํ๋๋ก ํ์๋ค.