<input />标签不适用于我的功能

时间:2016-11-19 21:45:33

标签: javascript input

我的HTML <input>标记无法使用我的Javascript函数。

<center>
<input type="text" id=user onsubmit="UserChoice" placeholder="Make your choice...">
</center>
var rock = 1;
var paper = 2;
var scissors = 3;
var spock = 4;
var lizard = 5;

function Game() {

    var ComputerChoice = ((Math.Random() * 5) + 1);
    var UserChoice = ""

    if (UserChoice == ComputerChoice) {
        document.getElementById("user").innerHTML = "Its a tie! Your opponent also chose" + ComputerChoice;
    }

    if (ComputerChoice == 1) {
        return "Rock"
    }

    if (ComputerChoice == 2) {
        return "Paper"
    }

    if (ComputerChoice == 3) {
        return "Scissors"
    }

    if (ComputerChoice == 4) {
        return "Spock"
    }

    if (ComputerChoice == 5) {
        return "Lizard"
    }

    if (ComputerChoice == 1 && UserChoice == 2) {
        document.getElementById("user").innerHTML="You won! The computer chose" + ComputerChoice;
    }
}

2 个答案:

答案 0 :(得分:0)

听起来这就是你所需要的:

1)我为Math.random()

更改了Math.Random()

2)在比较值

后添加了一个显示消息的div

3)我还添加了一行代码来获取用户插入的值

 document.getElementById("user").value

以下是解决方案:

&#13;
&#13;
var rock = 1;

   var paper = 2;

   var scissors = 3; 

   var spock = 4;

   var lizard = 5;

function Game() {

   var ComputerChoice = Math.floor(Math.random() * 3 + 1);
   alert("Computer input was: " + ComputerChoice)

   var UserChoice = document.getElementById("user").value;

   if (UserChoice == ComputerChoice){
      document.getElementById("result").innerHTML = "Its a tie! Your opponent also chose " + ComputerChoice;
      return false;

   } 

      if (ComputerChoice == 1){
      return "Rock"
   }

      if (ComputerChoice == 2){
      return "Paper"
   }

      if (ComputerChoice == 3){
      return "Scissors"
   }

      if (ComputerChoice == 4){
      return "Spock"
   }

      if (ComputerChoice == 5){
      return "Lizard"

   }

 if (ComputerChoice == 1 && UserChoice == 2){

     document.getElementById("result").innerHTML="You won! The computer chose" + ComputerChoice;
     return false;

 }

}
&#13;
<form onsubmit="return Game()">
  <center><input type="text" id=user  placeholder="Make your choice..."></center>
  <center><input type = "submit"></center>
</form>
<div id = "result"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

永远不会为UserChoice分配值

您正在将UserChoiceComputerChoice进行比较,但永远不会为UserChoice分配值(空字符串除外)。所以这种比较毫无意义。

var UserChoice = ""

您需要从DOM中获取用户的选择。

var UserChoice = document.getElementById('user').value;

未提示onsubmit

您似乎误解了onsubmit属性。它应该指向在表单提交上运行的函数。此外,它必须位于form标记中,而不是input标记。

<form onsubmit="Game()">
    <input type="text" id=user onsubmit="UserChoice" placeholder="Make your choice...">
    <input type="submit" value="Submit">
</form>

不推荐使用中心标记

最后,从HTML 4开始,<center>标记已弃用。要使元素居中,您可以使用CSS。

<style>
    center {
        text-align: center;
    }
</style>

<div class="center">
    <input id="user" ...>
</div>