2017-10-13 94 views
0

我想用Javascript和Im構建一個簡單的計算器,清理顯示內容時出現問題。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>

回答

6

你的方法名是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>

+0

感謝小費。 – Kingsfull123

1

的問題是,有其優先級高於原來的通話一個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>

+0

謝謝,我不知道。乾杯 – Kingsfull123