提问者:小点点

我的js函数在html页面中没有响应


null

function myfunc(){
    var x = Math.floor(Math.random() * 11);
    var y = parseInt(document.getElementById("enter a guess").value);
    if(y==x){
        alert("Right ans");

        document.body.style.backgroundColor = "green";
    }
    else
    {
        alert("wrong ans");
        document.body.style.backgroundColor = "red";
    }
}
<div class="center">
    <h1>Enter a guess from 1 to 10</h1>
    <input type="text" id="enter a guess" name="enter a guess" placeholder = "enter a guess">
    <br><br>
    <button class="button"; onclick="myFunc()">Guess</button>
</div>

null

我需要从用户的输入int从1到10,并产生一个从1到10的随机数,如果两者相等,并且用户点击猜测按钮,应该显示消息告诉他是对还是错,如果他是对的,页面背景颜色应该是绿色,否则如果是错的,应该是红色


共1个答案

匿名用户

您有多个问题:

id中不能有空格。也不能在按钮后添加分号

null

<div class="center">

    <h1>Enter a guess from 1 to 10</h1>
    
     <input type="text" id="enter_a_guess" name="enter a guess" placeholder = "enter a guess"><br><br>
    <button class="button" onclick="myFunc()">Guess</button>
</div>

    <script>
function myFunc(){
  var x = Math.floor(Math.random() * 11);
  var y = parseInt(document.getElementById("enter_a_guess").value);
  if(y==x){
    
    alert("Right ans");

    document.body.style.backgroundColor = "green";
  } else {
    alert("wrong ans");
    document.body.style.backgroundColor = "red";
  }
}
</script>