[英]JavaScript input output game
我一直在尝试制作猜旗游戏,但我不知道我在这里做错了什么。 生成随机图像工作得很好,但得到 output 没有。
<!DOCTYPE html>
<head></head>
<body>
<div>
<div>
<img id="image_shower" />
</div>
<div>
<button id="button1" onclick="get_random_image()">GENERATE</button>
</div>
<form>
What number is it? <input type="number" id="input1"></form><button id="button1"
onclick="submit_input()">SUBMIT</button></br>
<p id="output"></p>
</div>
<script>
function get_random_image() {
var random_index = Math.floor(Math.random() * 3) + 1;
if (random_index == 1)
document.getElementById('image_shower').src = `./js01img/1.png`
if (random_index == 2)
document.getElementById('image_shower').src = `./js01img/2.png`
if (random_index == 3)
document.getElementById('image_shower').src = `./js01img/3.png`
}
function submit_input() {
var x = document.getElementById("input1").value;
if (x == random_index) {
result = "correct";
} else {
result = "wrong";
}
document.getElementById("output").innerHTML = result;
}
</script>
</body>
</html>
对不起,我知道这可能就像问如何使用勺子但我正在失去它。 感谢帮助。
您无法从按钮值中获取输入值。 您必须先创建一个输入元素,然后从 JavaScript 或 jQuery 中检索它。
您还在错误的 scope 中声明了您的随机索引值。 它需要在 function 之外。
这是一个快速修复:
let random_index=-1;
function get_random_image() {
random_index = Math.floor(Math.random() * 3) + 1;
if (random_index == 1)
document.getElementById('image_shower').src = `./js01img/1.png`
if (random_index == 2)
document.getElementById('image_shower').src = `./js01img/2.png`
if (random_index == 3)
document.getElementById('image_shower').src = `./js01img/3.png`
}
function submit_input() {
var x = document.getElementById("input1").value;
if (x == random_index) {
result = "correct";
} else {
result = "wrong";
}
document.getElementById("output").innerHTML = result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.