我在codepen上练习,出于某种原因,hte javascript代码中的AddtoInput函数似乎没有运行/编译。不确定它是否与html中的onclick有关,它很简单所以我不这么认为..
HTML代码
<div id = "container">
<div id="header">Calculator</div>
<div id = "calculator">
<div id="top">
<div class="clear" onclick='Clear()'> C </div>
<div class="screen">
<input id="screen" type="text" placeholder="Let's do some math!"/></div>
</div>
<div class = "squares">
<span onclick = "AddtoInput(1)">1</span>
<span type="button" onclick="AddtoInput(2)">2</span>
<span type="button" onclick='AddtoInput(3)'>3</span>
<span class="operator add" onclick='oper(+)'>+</span>
<span type="button" onclick="AddtoInput(4)">4</span>
<span type="button" onclick="AddtoInput(5)">5</span>
<span type="button" onclick="AddtoInput(6)">6</span>
<span class="operator sub" onclick='oper(-)'>-</span>
<span type="button" onclick="AddtoInput(7)">7</span>
<span onclick="AddtoInput(8)">8</span>
<span type="button" onclick="AddtoInput(9)">9</span>
<span class="operator" onclick='oper(/)'>÷</span>
<span type="button" onclick="AddtoInput(0)">0</span>
<span>.</span>
<span class="equal" onclick='calc()'>=</span>
<span class="operator" onclick='oper(*)'>x</span>
<div>
</div>
</div>
Javascript代码:
var operators = ['+', '-', '*', '/'];
var StringOper = '';
var InString = 0;
var InString2 = 0;
var elem = document.getElementById("screen");
function AddtoInput(num) {
window.alert("I am In!!");
InString = InString*10;
InString = InString + num;
elem.value = InString;
}
function Clear(){
window.alert("I am In clear");
InString = 0;
elem.value = InString;
}
function oper(operator) {
for (var i= 0,i<4;i++){
if(operators[i] == operator)
StringOper = operator;
}
}
function calc (){
}
答案 0 :(得分:1)
问题出在你的for循环中。
将其重写为:
function oper(operator) {
for (var i = 0; i < 4; i++){
if(operators[i] == operator)
StringOper = operator;
}
}
它应该有用。
问题是您在初始化和条件<之间的for语句中使用了逗号而不是分号 /强>
查看MDN document on for loops了解详情。