简体   繁体   English

JavaScript计算器简单清除功能无法正常工作

[英]Javascript calculator simple clear feature not working

I am trying to build a simple calculator with Javascript and Im having issues when clearing display content. 我正在尝试使用Javascript和Im构建一个简单的计算器,在清除显示内容时遇到问题。

Can someone please have a look at my code and let me know why it is not working. 有人可以看看我的代码,让我知道为什么它不起作用。

Why won't setting the display value to an empty string work. 为什么不将显示值设置为空字符串呢? What am I doing wrong? 我究竟做错了什么? Tank you guys. 坦克你们。

 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> 

Your method name is conflicting with the id value , just change it to clear1 and it should work. 您的方法名称与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> 

The problem is that there is a document.clear function which is taking precedence over your original call. 问题是有一个document.clear函数优先于您的原始调用。 You can test this by typing document.clear into the console. 您可以通过在控制台中输入document.clear进行测试。

Try renaming your function to clearDisplay. 尝试将函数重命名为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM