javascript中的随机方程



function button(){
text1 = 4
var rand1 = Math.floor(Math.random() * text1);
var rand2 = Math.floor(Math.random() * text1);
var answer1 = rand1 + '+' + rand2;
var html = rand2 + '+' + rand1
document.write(html)
}
function check(rand1, rand2){
var text11 = document.getElementById('id').value;
var answer = rand1 + rand2;
if(answer == text11) {
document.write('correct!')
}
}

button()
<input type="text" id="id">
<button onclick="check()"> check </button>

我希望我的代码能够创建简单的方程式。你可以输入答案,它会告诉你是否正确。当我运行这个简单的代码,输入正确的答案并点击检查时,它不会显示正确。为什么会这样,我该如何修复?

有很多事情不是"漂亮的";方法它不起作用,因为rand1rand2未定义。将它们声明为全局的,或将它们与函数一起传递。除此之外,您不应该使用document.write,请将占位符替换为innerText。您应该将这些值与===进行比较,而不是与==进行比较

这里有一个例子,但请不要只是复制/过去:

<div id="placeholder"></div>
<input type="number" id="result">
<button onclick="check()"> check </button>
const input = document.getElementById('result');
const placeholder = document.getElementById('placeholder');
const randQuantifier = 4;
var random1 = getRandomNumber(), random2 = getRandomNumber();
placeholder.innerText = `${random1} + ${random2}`;
var answer = random1 + random2;
function getRandomNumber(){
return Math.floor(Math.random() * randQuantifier);
}
function check(){
if(answer === parseInt(input.value))
placeholder.innerText = "Correct!";
else
placeholder.innerText = "False!";
}

在您的代码中,check()需要两个参数rand1rand2,在从onclcik调用它时不会传递这两个参数。

以下代码应该可以工作,检查一下…

<html>
<body>
<script>
function button(){
text1 = 4
var rand1 = Math.floor(Math.random() * text1);
var rand2 = Math.floor(Math.random() * text1);
var answer1 = rand1 + '+' + rand2;
var html = rand2 + '+' + rand1
document.write(html)
return rand1 + rand2;
}
function check(){
var text11 = document.getElementById('id').value;
if(answer == text11) {
document.write('correct!')
}
}
var answer = button()
</script>
<input type="text" id="id">
<button onclick="check()"> check </button>
</body>
</html>

最新更新