从输入字段中的方程式

15 浏览
0 Comments

从输入字段中的方程式

我有三个输入框,我想要将它们的值相加。当我在第一个输入框中输入数字"5"时,控制台显示"0";当我在下一个输入框中输入数字"2"时,控制台会显示第一个输入框中的数字"5";当我在第三个输入框中输入数字"5"时,控制台会显示"7"。

为什么会出现这种情况,我应该如何修复它?

0
0 Comments

问题的出现原因:

在上述代码中,使用了onkeyup事件来触发obtainScoreOne()函数,但实际上应该使用onkeypress事件。onkeypress事件在输入值被设置之前被触发,而onkeyup事件在输入值被设置之后被触发。这导致了问题的出现。

解决方法:

将代码中的onkeyup事件替换为onkeypress事件即可解决问题。使用onkeypress事件可以确保在获取输入值之前触发函数,从而得到正确的计算结果。

以下是修改后的代码:




这样修改后,当用户在输入框中按下键盘时,obtainScoreOne()函数将被触发,获取输入值并进行计算,确保得到正确的结果。

0
0 Comments

问题出现的原因是在obtainScoreOne函数中,使用了document.querySelector来获取输入框的值,但是在输入框的HTML代码中,没有为obtainScoreOne函数传递参数。这导致在调用obtainScoreOne函数时,无法获取输入框的值,从而无法进行计算。

要解决这个问题,需要修改HTML代码,在调用obtainScoreOne函数时,传递输入框的值作为参数。可以通过在onkeyup事件中调用obtainScoreOne函数,同时传递输入框的值作为参数来实现。修改后的HTML代码如下:

<input id="roundOne" onkeyup="obtainScoreOne(this.value, document.querySelector('#roundTwo').value, document.querySelector('#roundThree').value)" type="number" value="0">            
<input id="roundTwo" onkeyup="obtainScoreOne(document.querySelector('#roundOne').value, this.value, document.querySelector('#roundThree').value)" type="number" value="0">          
<input id="roundThree" onkeyup="obtainScoreOne(document.querySelector('#roundOne').value, document.querySelector('#roundTwo').value, this.value)" type="number" value="0">

通过修改HTML代码,将输入框的值传递给obtainScoreOne函数后,即可正常获取输入框的值并进行计算。这样,问题就得到了解决。

0