他正在尝试学习java脚本,我的想法是数字的输入字段。 当用户填写数字时,我的脚本应将其放在段落或其他文本字段中。当用户在第一个tekst字段中填写另一个数字时,它会同时计算2个值。
是这样的吗?
var number = document.getElementById("getalInput");
var resultaat = document.getElementById("getalOutput")
number.onchange = function() {calculatie()};
function calculatie(){
resultaat.innerHTML = number.value + " + " + "next value" + " + " + "and so on";
resultaat.style.display = 'block';
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js" async></script>
</head>
<body>
<input type="text" id="getalInput">
<br>
<p id="getalOutput"></p>
</body>
</html>
答案 0 :(得分:1)
您可以为总和引入一个变量,并使用它来对值进行求和。
var number = document.getElementById("getalInput"),
resultaat = document.getElementById("getalOutput"),
sum = 0; // new varaibale
number.onchange = calculatie; // assign function directly for the event
function calculatie(){
sum += +number.value || 0; // get a number or zero for not number input
resultaat.innerHTML = sum;
}
<input type="text" id="getalInput"><br>
<p id="getalOutput"></p>
答案 1 :(得分:0)
var number = document.getElementById("getalInput");
var resultaat = document.getElementById("getalOutput")
number.onchange = function() {calculatie()};
function calculatie(){
if(!resultaat.innerHTML.trim()){
resultaat.innerHTML = number.value;
}else{
resultaat.innerHTML += " + " + number.value;
}
number.value = '';
resultaat.style.display = 'block';
}
&#13;
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js" async></script>
</head>
<body>
<input type="text" id="getalInput">
<br>
<p id="getalOutput"></p>
</body>
</html>
&#13;