【问题标题】:Javascript calculator simple clear feature not workingJavascript计算器简单清除功能不起作用
【发布时间】:2017-10-13 07:17:34
【问题描述】:

我正在尝试使用 Javascript 构建一个简单的计算器,但在清除显示内容时遇到了问题。

有人可以看看我的代码,让我知道为什么它不起作用。

为什么不能将显示值设置为空字符串。我究竟做错了什么?坦克你们。

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>

【问题讨论】:

    标签: javascript html calculator innerhtml


    【解决方案1】:

    您的方法名称是conflicting with the id value,只需将其更改为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>

    【讨论】:

      【解决方案2】:

      问题在于有一个 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>

      【讨论】:

        猜你喜欢
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 2018-02-02
        • 2015-12-10
        • 1970-01-01
        • 2020-10-21
        相关资源
        最近更新 更多