랜덤으로 생성된 숫자를 맞춰주는 프로그램을 만들어 자기소개 사이트에 넣기로 했다
아래는 사이트 주소
https://sanghunlee-711.github.io/wecode1stweek/PROJECTS.html
먼저 random으로 선정된 숫자와 대조시키기위해 사용자 임의기입을 위한 input tag를 생성했고 각자 id 와 class를 넣었다.
<label for = "guessField">Enter a guess</label>
<input type = "text" id = "guessField" class = "guessField">
<input type ="submit" value = "Submit guess"
class = "guessSubmit" id = "submitguess">
Math 객체를 이용하여 random한 숫자를 불러오게 시켰다.
Math.random()를 이용하여 0과 1 사이의 난수를 받아 그것의 *10을 하면 0~9사이의 값이 나올것이고
거기에 +1 을 한뒤 floor를사용하면 1~10사이의 값이 나오게 된다.
*Math.floor(x): 인수보다 작거나 같은 수 중에서 가장 큰 정수를 반환합니다.
const y = Math.floor(Math.random()*10+1);
x 변수는 querySelector()를 이용하여 guessField class에 있는 input tag 내에 사용자가 기입 할 value값을 가져오는 것으로 만들었다.
*document.querySelector(): 문서 내에서 주어진 선택자를 만족하는 첫 번째 Element를 반환합니다.
-> css 의 선택자라고 생각하면 편할듯.
const x = document.querySelector(".guessField").value;
조건문은 간단하게 변수두개의 일치 및 크기비교를 통해 alert를 띄우는것으로 작성되었고
내부에 template line 작성법을 적용해보았다.(별의미가 없음)
if(x == y)
{
alert(`Congratulation you guess right way!! The number is ${x} !`);
}
else if(x > y)
{
alert("Sorry try a smaller number");
}
else
{
alert("Sorry try a greater number");
}
querySelector를 통해 id sumbitguess인 submit 타입의 input form 클릭시 함수가 작동하도록 만들었다.
document.querySelector("#submitguess").onclick = function(){
};
클릭시 value값을 가져오기 위해 function 내부에 const x를 넣었음
끝
const y = Math.floor(Math.random()*10+1);
const guess = 1;
document.querySelector("#submitguess").onclick = function(){
const x = document.querySelector(".guessField").value;
if(x == y)
{
alert(`Congratualtion you guess right way The number is ${x} ! `);
}
else if(x > y)
{
alert("Sorry try a smaller number");
}
else
{
alert("Sorry try a greater number");
}
};
추후에 CSS로 좀 예쁘게 만들어야할 것 같다.
끝