【发布时间】:2018-11-04 10:54:53
【问题描述】:
我有一个学校项目要求我使用 if/else 语句构建一个基本的 Javascript 计算器。我对这种语言(以及一般编程)非常陌生,并且在应用我学到的语法以及如何成功解决问题方面遇到了麻烦。
继续代码:正如您将在 HTML 文件中的 cmets 中看到的,所有 javascript 代码都必须在 js 文件中。首先,我需要通过添加代码来绑定 onclick 事件,以将所有输入元素放入一个称为输入的数组(我已经完成),然后使用 for 循环遍历数组(我已经开始)。然后,在 for 循环中,我需要使用 if/else 语句跳过非按钮的输入元素,并将其他输入元素的 onclick 处理程序设置为调用其中的 calcu 变量的函数。这就是我在如何完成这项任务上陷入困境的地方。
我还需要确保将输入[i].id 也传递给计算。当然,我必须使用 if/else 语句来完成 calcu() 函数。
在 js 文件中,我插入了 cmets 以显示我的思考过程和我问自己解决问题的问题。
如果您能给我任何帮助或指导,我将不胜感激。谢谢!
var calcu = function(calcValue) {
/* "calc.output.value += "1";"" use to output numbers? */
if (calcValue) {
}
};
document.getElementById(inputs[i].id).onclick = calcu;
for (var i = 0; i <= inputs[id].length, i++) {
/* input button elements onlick handler needs to be set to (equal to?) a
function that calls the calcu variable inside of it */
if (input.type = button) {
console.log()
/* Need input that is not a button to be skipped*/
} else(input.type != button) {
}
}
<body>
<div id="content">
<div id="calculator-container">
<!-- DO NOT CHANGE THE FORM! Only use external JavaScript files -->
<form name="calc">
<label for="output">A Basic Calculator</label>
<!-- the name of the textbox is "output" -->
<input id="output" name="output" type="text" readonly>
<br>
<input type="button" id="1" value=" 1 ">
<input type="button" id="2" value=" 2 ">
<input type="button" id="3" value=" 3 ">
<input type="button" id="+" value=" + ">
<br>
<input type="button" id="4" value=" 4 ">
<input type="button" id="5" value=" 5 ">
<input type="button" id="6" value=" 6 ">
<input type="button" id="-" value=" - ">
<br>
<input type="button" id="7" value=" 7 ">
<input type="button" id="8" value=" 8 ">
<input type="button" id="9" value=" 9 ">
<input type="button" id="*" value=" x ">
<br>
<input type="button" id="c" value=" C ">
<input type="button" id="0" value=" 0 ">
<input type="button" id="equate" value=" = ">
<input type="button" id="/" value="÷">
</form>
</div>
</div>
</body>
【问题讨论】:
-
input.type = button将input.type赋值为 无论button是什么(在您的代码中未定义)... 和else(input.type != button)... 否则 不接受参数...你的意思是else if(input.type != button) -
你是如何定义称为输入的数组的?
-
您可以使用 IDE 或在线工具(如 jsfiddle.net)来查找代码中的语法错误,这些错误很多。您可以改为使用 inputs = document.getElementsByTagName("input") 并循环输入。目前您的输入未分配任何值
-
Kiran,谢谢你,我有点愚蠢,因为我没有考虑使用 getElementsTagName 方法。这有帮助。
标签: javascript if-statement calculator calc