【发布时间】:2017-03-15 22:09:55
【问题描述】:
嗨,请帮帮我,我的代码几乎完成了,但它只触发了最后一个按钮,即平方根选项。它应该看起来像一个计算器,它会打开一个带有文本框的弹出按钮,您可以在其中输入数字。我无法触发正确的操作。
<input type="button" value="Add" onclick="calculate('addition')">
<input type="button" value="Subtract" onclick="calculate('subtraction')">
<input type="button" value="Multiply" onclick="calculate('multiplication')">
<input type="button" value="Divide" onclick="calculate('division')">
<input type="button" value="Modulo" onclick="calculate('modulo')">
<input type="button" value="Pow" onclick="calculate('pow')">
<input type="button" value="Factorial" onclick="calculate('factorial')">
<input type="button" value="Sqrt" onclick="calculate('sqrt')">
<script>
function calculate(addition) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)+parseInt(y);
document.getElementById("z").value = z;
}
function calculate(subtraction) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)-parseInt(y);
document.getElementById("z").value = z;
}
function calculate(multiplication) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)*parseInt(y)
document.getElementById("z").value = z;
}
function calculate(division) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)/parseInt(y)
document.getElementById("z").value = z;
}
function calculate(modulo) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)%parseInt(y)
document.getElementById("z").value = z;
}
function calculate(pow) {
var x= prompt("What is your first number?", "");
var y= prompt("Raised to?", "");
var i=1
while (i<(parseInt(y)+1)) {
var z= parseInt(x)*parseInt(x)
i=parseInt(i)+1
}
document.getElementById("z").value = z;
}
function calculate(factorial) {
var x= prompt("What is your number?", "");
var i=1
var m=1
while (m<(parseInt(x))) {
i=parseInt(i)*((parseInt(m)+1))
m=parseInt(m)+1
}
document.getElementById("z").value = i;
}
function calculate(sqrt) {
var x= prompt("What is your number?", "");
i=1
while (i%parseInt(x)!=0) {
z=(parseInt(x)%i)
i=parseInt(i)+1
}
z=Math.sqrt(parseInt(x))
document.getElementById("z").value = z;
}
</script>
【问题讨论】:
-
呃,您多次定义该函数。函数名必须是唯一的......你应该有
function calculate(type) { if (type=='addition') { ... } else if (.....)-type 的东西,很可能。如果你做过任何基本的调试,比如检查浏览器的错误控制台,你就会被告知这个问题。
标签: javascript html json loops if-statement