산수 문제 풀이 사이트 만들어보기
1) 유저의 입력값이 정답인지 아닌지 채점해줘야한다.
2) 총 맞은 개수를 '채점' 버튼을 누를 때 화면에 보여준다.
3) 문제는 랜덤으로 출제된다. 단, 오직 사칙연산 문제만 출제된다.
4) '다시' 버튼을 누르면 새로운 문제가 출제되고, 맞은 개수와 유저 입력값이 초기화된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>산수 문제 풀이</title>
<style>
td
{
padding-left:10px;
padding-right:10px;
}
</style>
<script>
function clac() // 유저의 입력값이 정답인지 봐주는 함수
{
let total=0; // 초기화
let questionArray=document.getElementsByClassName("question"); // 여러개니깐 배열로 짜준다.
let answerArray=document.getElementsByClassName("answer");
for(i=0; i<questionArray.length; i++)
{
let question = questionArray[i].innerHTML;
let correctanswer = eval(question); // eval은 계산함수
let useranswer = answerArray[i].value;
//console.log(answerArray[i].value);
//console.log("useranswer :"+ useranswer);
console.log("parseInt(useranswer) : " + parseInt(useranswer));
console.log("correctanswer: " + correctanswer);
// 경우의 수 3개 : 답이 없거나 문자로 입력 / 정답 / 오답일 경우
if(useranswer=="" || isNaN(useranswer)) // 답이 없거나
{
total += 0;
questionArray[i].style.textDecoration = "line-through";
}
else if(parseInt(useranswer)==correctanswer) // 정답
{
total += 1;
questionArray[i].style.textDecoration = "none";
}
else // 오답
{
total += 0;
questionArray[i].style.textDecoration = "line-through";
}
}
document.getElementById("score").innerHTML=total;
}
function makeExp() // 랜덤으로 문제가 나오게 하는 함수
{
let questionArray=document.getElementsByClassName("question");
let answerArray=document.getElementsByClassName("answer");
for(i=0; i<questionArray.length; i++)
{
let num1 = Math.floor(Math.random()*20)+1;
let num2 = Math.floor(Math.random()*20)+1;
let op = Math.floor(Math.random()*4); // operator=연산자 사칙연산이어서 4개 랜덤
let operator = "+"; // 변수 operator 초기화
switch(op)
{
case 0: operator = "+"; break;
case 1: operator = "-"; break;
case 2: operator = "*"; break;
case 3: operator = "/"; break;
}
questionArray[i].innerHTML = num1 + operator + num2;
questionArray[i].style.textDecoration = "none";
answerArray[i].value = ""; // 초기화
document.getElementById("score").innerHTML = 0; // 초기화
}
}
</script>
</head>
<body onload = "makeExp()">
<h3>산수 문제를 풀어 봅시다.</h3>
<h4>수식을 계산하여 답을 입력하고 채점 버튼을 누르세요.</h4>
<hr>
<form>
<table>
<tr>
<td class="question">5*6</td>
<td><input class="answer" type="text" size="8"></td> <!--size는 최대 글자수-->
</tr>
<tr>
<td class="question">7+5*3</td>
<td><input class="answer" type="text" size="8"></td>
</tr>
<tr>
<td class="question">23*2</td>
<td><input class="answer" type="text" size="8"></td>
</tr>
<tr>
<td class="question">35-7</td>
<td><input class="answer" type="text" size="8"></td>
</tr>
<tr>
<td><input type="button" onclick="clac()" value="채점"></td>
<td><span id="score">0</span>
<button type="button" onclick="makeExp()"> 다시 </button></td>
</tr>
</table>
</form>
</body>
</html>
'Java Script' 카테고리의 다른 글
HTML + 자바스크립트로 계산기 만들기 (0) | 2020.08.26 |
---|