我正处于学习 JS 的初级阶段。我正在尝试创建一个页面,用户可以在文本字段中输入数字。用户可以按 Enter 键添加另一个号码。当用户按下回车键时,输入字段需要被清除
输入的金额必须加在一起,并且其总数必须显示在第二个文本框中。
我的 HTML:
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
我的JS:
input = document.getElementById("input");
input.onkeypress = function(event) {
ceckKey(event);
};
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
input.value = "";
}
var number = +input.value;
return number;
}
var total = 0
total += checkKey();
document.getElementById("output").value = total;
按键适用于所有浏览器。问题是我无法对数字求和。如果我把它放在按键函数中,那么每次你再次按回车键时,数字就会被清除。
希望大家帮忙!
最佳答案
在清除之前获取该值。
var input = document.getElementById("input");
var output = document.getElementById("output");
var total = 0;
input.onkeypress = function(e) {
if (e.keyCode == 13 || e.key == 13) {
total += +input.value;
output.value = total;
input.value = "";
}
};
<input type="number" id="input">
<p>Uw totaal:</p>
<input type="number" id="output">
关于javascript - 当按下 'Enter' 时,对输入求和并将其清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47731703/