首页 > 解决方案 > 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!

标签: htmlbuttoninputlogic

解决方案


不会撒谎,你的代码很混乱。你应该把它清理干净。您正在尝试访问从未定义过的变量 ( 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。


推荐阅读