[英]Javascript calculator simple clear feature not working
我正在尝试使用Javascript和Im构建一个简单的计算器,在清除显示内容时遇到问题。
有人可以看看我的代码,让我知道为什么它不起作用。
为什么不将显示值设置为空字符串呢? 我究竟做错了什么? 坦克你们。
function testing(button){ var x = button.value; document.getElementById("display").innerHTML+=x; } function clear() { document.getElementById("display").innerHTML = ""; }
<body> <input type="button" id="one" value="1" onClick="testing(this)"> <input type="button" id="one" value="2" onClick="testing(this)"> <input type="button" id="one" value="3" onClick="testing(this)"> <input type="button" id="clear" value="clear" onClick="clear()"> <h1 id="display"></h1> </body>
您的方法名称与id值冲突 ,只需将其更改为clear1
。
function testing(button){ var x = button.value; document.getElementById("display").innerHTML+=x; } function clear1(){ document.getElementById("display").innerHTML = ""; }
<body> <input type="button" id="one" value="1" onClick="testing(this)"> <input type="button" id="one" value="2" onClick="testing(this)"> <input type="button" id="one" value="3" onClick="testing(this)"> <input type="button" id="clear" value="clear" onClick="clear1()"> <h1 id="display"></h1> </body>
问题是有一个document.clear函数优先于您的原始调用。 您可以通过在控制台中输入document.clear
进行测试。
尝试将函数重命名为clearDisplay。
function testing(button){ var x = button.value; document.getElementById("display").innerHTML+=x; } function clearDisplay(){ document.getElementById("display").innerHTML = ""; }
<body> <input type="button" id="one" value="1" onClick="testing(this)"> <input type="button" id="one" value="2" onClick="testing(this)"> <input type="button" id="one" value="3" onClick="testing(this)"> <input type="button" id="clearDisplay" value="clear" onClick="clearDisplay()"> <h1 id="display"></h1> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.