Javascript 来自输入字段的公式
我有三个输入,我想添加,当我放置我的第一个数字“5”console.log显示“0”下一个输入字段我输入“2”这将console.log第一个输入字段的数字“5”第三个我输入“5”我在console.log“7”中看到 为什么会发生这种情况,我该如何解决它请Javascript 来自输入字段的公式,javascript,math,Javascript,Math,我有三个输入,我想添加,当我放置我的第一个数字“5”console.log显示“0”下一个输入字段我输入“2”这将console.log第一个输入字段的数字“5”第三个我输入“5”我在console.log“7”中看到 为什么会发生这种情况,我该如何解决它请 <input id="roundOne" onkeypress="obtainScoreOne()" type="text">
<input id="roundOne" onkeypress="obtainScoreOne()" type="text">
<input id="roundTwo" onkeypress="obtainScoreOne()" type="text">
<input id="roundThree" onkeypress="obtainScoreOne()" type="text">
在设置输入值之前触发了
onkeypress
,请尝试onkeypup
:
函数mathScore(x,y,z){
返回(x+y+z);
}
函数获取ScoreOne(){
//收集数据
设n1,n2,n3,和;
n1=编号(document.querySelector('#roundOne')。值);
n2=编号(document.querySelector('#roundTwo')。值);
n3=编号(document.querySelector('#roundThree')。值);
总和=数学分数(n1、n2、n3);
//显示结果
控制台日志(总和);
}
我希望这能有所帮助
函数获得一个(n1、n2、n3){
var n1=parseInt(document.querySelector('#roundOne').value);
var n2=parseInt(document.querySelector('#roundTwo').value);
var n3=parseInt(document.querySelector('#roundThree').value);
var和;
总和=n1+n2+n3;
控制台日志(总和);
回报金额;
}
您实际上不需要为此使用数字。您可以使用parseInt()。此外,您没有先检查值是否为空。与其绑定到keypress,不如绑定到输入事件。这是否回答了您的问题?特里回答了这个问题!非常感谢。
function mathScore(x, y, z){
return (x + y + z);
}
function obtainScoreOne() {
//collect data
let n1, n2, n3, sum;
n1 = Number(document.querySelector('#roundOne').value);
n2 = Number(document.querySelector('#roundTwo').value);
n3 = Number(document.querySelector('#roundThree').value);
sum = mathScore(n1, n2, n3);
//Display result
console.log(sum);
}