0

我是 Javascript 新手,正在上课以了解更多信息。我的部分作业是制作一个按钮,点击时会提示您输入所需的 cookie 数量。然后给你一个总数。每个 cookie 的价格取决于购买的 cookie 数量。

这就是我所拥有的。当我尝试调试器时,我在未定义的第 25 行被告知我的 else 语句。

所以基本上它循环然后给出 Total: $NaN 并且不会停止循环。

任何帮助,将不胜感激。

    <script>
        function buyCookies()
        {
            var numCookiesP = document.getElementById("numCookies");
            numCookiesP.innerHTML = parseInt (prompt("How many cookies would you like to buy?"));

            if(numCookies <= 5)
            {
                document.write("Total: $" + (numCookies * 1.25)).toFixed(2);
            }
            else if(numCookies <= 11)
            {
                document.write("Total: $" + (numCookies * 1.15)).toFixed(2);
            }
            else
            {
                document.write("Total: $" + (numCookies * 1.00)).toFixed(2);
            }

        }

    </script>
</head>
<body>
    <input type="button" value="Cookies" onclick="buyCookies()">

    <div>
        <p id="numCookies"</p>

    </div>
4

2 回答 2

0

您可能还需要调整其他一些东西,但以下内容至少应该清除 $NaN:

<script>
        function buyCookies()
        {
            var numCookies = parseInt (prompt("How many cookies would you like to buy?"));
            var numCookiesP = document.getElementById("numCookies").innerHTML;

            if(numCookies <= 5)
            {
                document.write("Total: $" + (numCookies * 1.25).toFixed(2));
            }
            else if(numCookies <= 11)
            {
                document.write("Total: $" + (numCookies * 1.15).toFixed(2));
            }
            else
            {
                document.write("Total: $" + (numCookies * 1.00).toFixed(2));
            }

        }

    </script>
</head>
<body>
    <input type="button" value="Cookies" onclick="buyCookies()">

    <div>
        <p id="numCookies"></p>

    </div>
于 2013-04-29T21:58:17.553 回答
0

有两个问题:

  • 您不能document.write在已加载的文档中使用 - 调用它将覆盖当前文档。设置innerHTML(或类似的 DOM 操作)是要走的路。document.write仅用于在加载文档时将脚本标签或类似内容直接写入 html 解析器流 - 您永远不会真正使用它。
  • 您没有声明和初始化numCookies变量 - 它不包含提示中解析的数字,因此计算 yield NaN

我猜你想要这个:

function buyCookies() {
    var numCookiesP = document.getElementById("numCookies");
    var numCookies = parseInt(prompt("How many cookies would you like to buy?"), 10);
    var factor = 1.0;
    if (numCookies <= 5) {
        factor = 1.25;
    } else if (numCookies <= 11) {
        factor = 1.15;
    }
    numCookiesP.innerHTML = "Total: $" + (numCookies * factor).toFixed(2);
}
于 2013-04-29T22:16:39.030 回答