我是Javascript的新手,正在上课以了解更多信息。我的家庭作业的一部分是制作一个按钮,点击时会提示您需要多少个cookie。然后给你一个总数。每个cookie的价格取决于购买的cookie数量。
这就是我所拥有的。当我尝试调试器时,我在第25行的未定义中告诉我的其他声明。
所以基本上它循环然后给出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>
答案 0 :(得分: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>
答案 1 :(得分:0)
有两个问题:
document.write
- 调用它将覆盖当前文档。设置innerHTML
(或类似的DOM操作)是可行的方法。 document.write
仅用于在加载文档时直接将脚本标记或类似内容编写到html解析器流中 - 您永远不会真正使用它。numCookies
变量 - 它不包含提示中已解析的数字,因此计算结果为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);
}