计算器第一次工作正常,但在我使用重置按钮后,它退出正常工作。 (注意:我只能设置乘法,直到我可以调试它)。我刚刚开始学习如何使用JavaScript。任何帮助都会很棒。
这是我的HTML代码:
var input = "";
var firstInput = "";
var secondInput = "";
var answer = "";
$(".numbers").click(function(){
$("#topBar").text(input += $(this).text())
});
function operation() {
firstInput = input;
$("#topBar").empty();
$(".numbers").click(function(){
$("#topBar").text(secondInput += $(this).text())
});
}
$("#buttonx").click(function(){
if(input !== ""){
operation();
}
});
$("#buttonEqual").click(function(){
answer = firstInput * secondInput;
$("#topBar").text(answer);
});
$("#resetButton").click(function(){
input = "";
firstInput = "";
secondInput = "";
answer ="";
$("#topBar").empty();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="container">
<div id="topBar"></div>
<div class="row">
<div class="butStyle">
<button class="numStyle numbers" id="button7">7</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button8">8</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button9">9</button>
</div>
<div class="butStyle">
<button class="numStyle operation" id="buttonDivide">÷</button>
</div>
</div>
<div class="row">
<div class="butStyle">
<button class="numStyle numbers" id="button4">4</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button5">5</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button6">6</button>
</div>
<div class="butStyle">
<button class="numStyle operation" id="buttonx">x</button>
</div>
</div>
<div class="row">
<div class="butStyle">
<button class="numStyle numbers" id="button1">1</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button2">2</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="button3">3</button>
</div>
<div class="butStyle">
<button class="numStyle operation" id="buttonMinus">-</button>
</div>
</div>
<div class="row">
<div class="butStyle">
<button class="numStyle numbers" id="button0">0</button>
</div>
<div class="butStyle">
<button class="numStyle numbers" id="buttonDot">.</button>
</div>
<div class="butStyle">
<button class="numStyle" id="buttonEqual">=</button>
</div>
<div class="butStyle">
<button class="numStyle operation" id="buttonAdd">+</button>
</div>
</div>
<button id ="resetButton">Reset</button>
</div>
&#13;
答案 0 :(得分:1)
empty()函数删除所选元素的子节点,我想你可能只想用其他内容替换内容(如空字符串或0)或使用html()函数代替。
答案 1 :(得分:1)
问题来自每次按下操作员时注册新的点击监听器的事实:
$(".numbers").click(function(){
$("#topBar").text(secondInput += $(this).text())
});
如果你想保持这种逻辑(我会重构很多东西:)),你需要确保在调用这段代码时不要调用它。