Js代码,要求50以内加减乘除随机产生20题,带检验
<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
script
>
var count = 0;
var con;
function getRandom() {
return Math.floor(Math.random()*51);
}
function getOperator() {
var arr = ['+', '-', '×', '÷'];
return arr[Math.floor(Math.random()*arr.length)];
}
function validate(num1, op, num2) {
if (op === '÷' && num2 === 0) return false;
if (num1%num2 != 0) return false;
if (op === '-' && num1 < num2) return false;
return true;
}
function create() {
con = document.getElementById("content");
var num1 = getRandom();
var num2 = getRandom();
var op = getOperator();
var opTemp = op;
if (op === '×') opTemp = '*';
if (op === '÷') opTemp = '/';
var answer = eval(num1 + (opTemp) + num2);
if(!validate(num1, op, num2)) return;
var str = num1 + " " + op + " " + num2 + " =" + " " + "<
input
type
=
'text'
style
=
'width:30px;'
/>";
var newNode = document.createElement("div");
newNode.className = "sss";
newNode.setAttribute('data-answer', answer);
newNode.style.width = "10px;";
newNode.innerHTML = str;
con.appendChild(newNode);
count ++;
}
function load() {
while (count < 20) {
create();
}
}
function getAnswer() {
for (var i = 0, c = con.childNodes; i < c.length; i ++) {
if (c[i].className != 'sss') continue;
var input = document.getElementsByTagName('input')[i-1];
var value = input.value;
if (c[i].getAttribute('data-answer') == value) {
input.style.backgroundColor = "green";
} else {
input.style.backgroundColor = "red";
}
}
}
</
script
>
</
head
>
<
body
onload
=
"load();"
>
<
div
id
=
"content"
>
</
div
>
<
div
>
<
button
onclick
=
"getAnswer();"
>提交</
button
>
<
button
onclick
=
"location = location;"
>重置</
button
>
</
div
>
</
body
>
</
html
>