我在完成一个简单的JS数学游戏时遇到了麻烦

时间:2014-06-17 05:38:04

标签: javascript button onclick

我的onclick函数正常运行,但问题是jQuery因为某些原因不能为我工作,所以我把它拿出去了,但我不知道如何禁用它onclick没有使用jQuery:如何禁用按钮onclick并让它在正确的情况下保持禁用状态(如果不正确则重置?我还需要制作它使numOnenumTwo重新计算另一个随机数,如果它等于禁用按钮的ID,那么我猜测我已经改变了do while循环我必须确保numTwo永远不等于numOne,但我不确定如何做到这一点。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Lemon Squares - Grade 1 Edition</title>
    </head>
    <body id="bodyId">
        <script type="text/javascript">
            var button = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
            var numbers = new Array();  
            for (var i=0; i<16; i++)
            {
                var randomNumber = Math.floor(Math.random()*9);
                numbers[i] = document.createElement("button");
                numbers[i].innerHTML = button[randomNumber];
                numbers[i].setAttribute("type", "button");
                numbers[i].setAttribute("id", button[i]);
                numbers[i].setAttribute("onclick", "onClick('" + button[randomNumber] + "')");
                numbers[i].setAttribute("value", button[randomNumber]);
                document.getElementById("bodyId").appendChild(numbers[i]);
                if (i == 3 || i == 7 || i == 11) 
                {
                document.write("<br>");
                }
            }
            var numOne = (Math.ceil(Math.random()*15)).toString();
            var numTwo = (Math.ceil(Math.random()*15)).toString();
            do
            {
                numTwo = Math.ceil(Math.random()*15).toString();
            }
            while (numTwo == numOne);
            var numberOne = document.getElementById(numOne).value;
            var numberTwo = document.getElementById(numTwo).value;
            var answer = parseInt(numberOne) + parseInt(numberTwo);
            var total = 0
            function onClick(x)
            {
                x = parseInt(x);
                total += x;
                if (total > answer)
                {
                alert("Sorry, try again.")
                total = 0
                }
                else if(total == answer)
                {
                alert("Congratulations, you did it!");
                total = 0
                }        
            }       
            document.write("<br> Pick two numbers that add up to: " + answer);
        </script>       
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

我认为你这是错误的做法。

游戏的逻辑是(如果我理解正确的话):

  • 选择&#34; 1到n&#34;(n是所有可用按钮/项目的数量)随机项目数
  • 获取所选项目值的总和并显示给用户
  • 记录并添加用户选择的值,直到达到目标并按用户跟踪所选项目是一个数组
  • 如果所选项目总和正确,则禁用所选项(仅向按钮添加禁用属性)项目,并从步骤1中获取,其中n是剩余项目数

所以对你的问题:

单击每个按钮

执行以下步骤:

  1. 将值添加到数组
  2. 获取数组中值的总和
  3. 将总和与答案进行比较
    • 如果总和小于答案,则不做任何事情并等待下一次点击
    • 如果总和等于答案
      1. 禁用数组中的按钮
      2. 清除所选项目数组
      3. 创建新答案
    • 如果总和超过答案,请清除所选项目数组并重新开始
  4. 我希望这会有所帮助。