This question already has answers here:
How to force JS to do math instead of putting two strings together
                                
                                    (10个回答)
                                
                        
                2年前关闭。
            
        

我的脚本错过了什么吗?

就像当我按下减号(-)按钮时一切正常,但是当我按下加号(+)按钮时,计算器出错了。它的显示1,11,21,〜一切都以1.结尾。

这是我的代码:



function myFunctionDown() {
    var x = document.getElementById("myNumber").value;
    var y = 1;
    var a = (x-y)*1;
    document.getElementById("myNumber").stepUp(-1);
    document.getElementById("demo").innerHTML = a;
}
function myFunctionUp() {
    var x = document.getElementById("myNumber").value;
    var y = 1;
    var a = (x+y)*1;
    document.getElementById("myNumber").stepUp(1);
    document.getElementById("demo").innerHTML = a;
}

<button onclick="myFunctionDown()">-</button>
<input type="number" id="myNumber" value="0">
<button onclick="myFunctionUp()">+</button>
<br/><br/>
$ <span id="demo">0</span>





我从w3school获得了这段代码,并以非常基础的知识对其进行了编辑。我有什么想念的吗?还是您有更好的方法来编写它?

最佳答案

您需要将输入值解析为数字-因为所有输入值实际上都是字符串。



function myFunctionDown() {
    var x = parseInt(document.getElementById("myNumber").value);
    var y = 1;
    var a = (x-y)*1;
    document.getElementById("myNumber").stepUp(-1);
    document.getElementById("demo").innerHTML = a;
}
function myFunctionUp() {
    var x = parseInt(document.getElementById("myNumber").value);
    var y = 1;
    var a = (x+y)*1;
    document.getElementById("myNumber").stepUp(1);
    document.getElementById("demo").innerHTML = a;
}

<button onclick="myFunctionDown()">-</button>
<input type="number" id="myNumber" value="0">
<button onclick="myFunctionUp()">+</button>
<br/><br/>
$ <span id="demo">0</span>

关于javascript - JS的数学计算器脚本错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51304002/

10-11 13:24