我只是在尝试制作一个基于移动设备的简单计算器。到目前为止,我设法显示了按一定字符数限制的数字。我正在尝试使其清除用作显示的h1标签内的数字。
我尝试使用.innerHTML = ""
,但是没有用。我该如何解决?
HTML
<body>
<h1 id="display">Calculator</h1>
<div class="buttons container" id="arithmetic">
<button onclick="clear()" onkeypress="clear()">AC</button>
<button><sup>+</sup>⁄<sub>−</sub></button>
<button>%</button>
<button>÷</button>
<button onclick="number(7)" onkeypress="number(7)">7</button>
<button onclick="number(8)" onkeypress="number(8)">8</button>
<button onclick="number(9)" onkeypress="number(9)">9</button>
<button>×</button>
<button onclick="number(4)" onkeypress="number(4)">4</button>
<button onclick="number(5)" onkeypress="number(5)">5</button>
<button onclick="number(6)" onkeypress="number(6)">6</button>
<button>−</button>
<button onclick="number(1)" onkeypress="number(1)">1</button>
<button onclick="number(2)" onkeypress="number(2)">2</button>
<button onclick="number(3)" onkeypress="number(3)">3</button>
<button>+</button>
<button>.</button>
<button id="doubleSpace" onclick="number(0)" onkeypress="number(0)">0</button>
<button>=</button>
</div>
<div class="calcOptions container">
<button>Arithmetic</button>
<button>Algebra</button>
<button>Calculus</button>
<button>Statistics</button>
</div>
</body>
JavaScript
var currentQuery;
var pastQuery;
var queryLength = document.getElementById("display").innerHTML.length;
function number(n) {
if (document.getElementById("display").innerHTML == "Calculator") {
document.getElementById("display").innerHTML = "";
}
if (queryLength >= 15) {
} else {
currentQuery = document.getElementById("display").innerHTML;
currentQuery += n;
document.getElementById("display").innerHTML = currentQuery;
}
}
function clear() {
currentQuery = "";
document.getElementById("display").innerHTML = currentQuery;
}
答案 0 :(得分:1)
您无法使用 clear()命名javascript函数,并且在文档准备好替换您的代码之后,应设置 queryLength 的值:
var currentQuery;
var pastQuery;
var queryLength;
document.addEventListener("DOMContentLoaded", function(event) {
var queryLength = document.getElementById("display").innerHTML.length;
})
function number(n) {
if (document.getElementById("display").innerHTML == "Calculator") {
document.getElementById("display").innerHTML = "";
}
if (queryLength >= 15) {
} else {
currentQuery = document.getElementById("display").innerHTML;
currentQuery += n;
document.getElementById("display").innerHTML = currentQuery;
}
}
function clearValue() {
currentQuery = "";
document.getElementById("display").innerHTML = currentQuery;
}
和带有以下按钮的清除按钮:
<button onclick="clearValue()" onkeypress="clearValue()">AC</button>
答案 1 :(得分:0)
您可以尝试使用.innerText = ""
。
答案 2 :(得分:0)
问题在于此本机函数document.clear()已经使用了函数 clear 的名称。以下是为何调用此本机函数而不是您的函数的更深入了解:Is “clear” a reserved word in Javascript?。
解决方案是将您的clear()
函数重命名为其他名称,例如allcancel()