html - Stuck on buttons and text input in html
问题描述
I'm currently working on a simple flag guessing game, where the user sees a flag and input's the country it is, but I'm finding it hard to take a value from the text input and put it into logic. My function for the button does run but doesn't make it to the if statements, seemingly not reading the text in the input.
<!DOCTYPE html>
<html>
<head>
<title>The America's</title>
</head>
<body>
<img src = "Colombia.png">
</br>
<p><em>The flag shown above is which countries flag?</em></p>
<h1 id="flag">...</h1>
<h2 id = "guess">...</h2>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<!--
<button id="enter">Enter</button> -->
<button id = "button_enter" onclick="guess()">Enter</button>
<script>
function guess(){
alert("f")
flag.textContent = guess.value;
if (guessfun == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
alert("Yes")
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
alert("No")
}
}
onclick = guess();
</script>
</body>
</html>
Any help would be greatly appreciated!
解决方案
不会撒谎,你的代码很混乱。你应该把它清理干净。您正在尝试访问从未定义过的变量 ( flag
, guess
)。要访问元素,请使用 document.getElementById()。我也没有看到 flag.textContent 的用途。您应该在检查时直接访问输入。
function guess(){
var guess = document.getElementById("guessfun").textContent;
var result = document.getElementById("result");
if (guess == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
}
}
此外,您可能应该从底部删除 onclick。
推荐阅读
- wordpress - Wordpress Customizer Image 仅显示一个数字
- vue.js - 在 vue-test-utils 中的存根上使用 key 修饰符发出 keydown 事件
- windows - 分支开关上的文件夹大小写不变
- php - 在 Laravel 中使用 Redis 缓存图像?
- javascript - 文件不会在 Notepad++ 中另存为 JavaScript 扩展
- node.js - 登录后无法获取 jwt 令牌
- mongodb - MongoDB oplog 包含许多 Noop
- postgresql - postgres 10 对等身份验证失败
- c# - 在反序列化 JSON 文件时不使用完整路径
- matlab - 如何在 MATLAB 中实现人口普查变换